views:

76

answers:

2

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!

+5  A: 

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++);
}
Mark Ransom
Thank you very much! Solved.
citizencane
+2  A: 

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) {...}
UncleBens