citizencane
citizencane

Reputation: 183

STL iterator into constructor

Id' like to know how to write a constructor for a custom class (a linked list in this case) that accepts any STL input iterator. I have already created a custom Iterator class which is tied to my List class.

This works fine.

template <typename T>  
List<T>::List(Iterator beg, Iterator end) : first_(0) {  
    while (beg != end)  
        insertLast(*beg++);
}

I've managed to create a constructor that receives list iterators like this.

List<T>::List(typename list<T>::iterator s, typename list<T>::iterator e) :
    first_(0) {  
    while (s != e)   
        insertLast(*s++);

My STL-fu is not really up to snuff on how to go about generalizing this to accept any input iterator
Any help out there?

Thanks!

Upvotes: 1

Views: 2166

Answers (2)

UncleBens
UncleBens

Reputation: 41331

That could be simply a templated constructor.

template <class T>
class List
{
    public:
    template <class Iter>
    List(Iter from, Iter to);
    ...
};

template <class T>
template <class Iter>
List<T>::List(Iter from, Iter to) {...}

Upvotes: 3

Mark Ransom
Mark Ransom

Reputation: 308158

I think it's as simple as this:

template <typename T, typename Iterator>  
List <T>::List(Iterator beg, Iterator end) : first_(0) {  
    while (beg != end)  
        insertLast(*beg++);
}

Upvotes: 5

Related Questions