Iterator help

Could someone tell me why this is invalid with a list? This function worked fine with a vector so I'm a bit confused as to what went wrong.


Here is the function call:
 
print(list1.begin(), list1.end());

Here is the function definition:
1
2
3
4
5
6
7
8
9
10
11
12
template <class Iter>
void print(Iter first, Iter  limit)
{
while (first != limit) {
    std::cout << *first;
    if(first + 1 != limit)
    {
      std::cout << " ";
    }
    ++first;
  }
}


On line six I am getting the error "no match for 'operator+'"
Last edited on
std::list has bidirectional iterators for which operator + is not defined, something on the following lines perhaps:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <list>
#include <vector>

template <class Iter>
void print(Iter first, Iter  limit)
{
    while (first != limit)
    {
        std::cout << *first << " ";
        ++first;
    }
    std::cout << "\n";
}

int main()
{
    std::list<int> myList{1, 2, 3, 4, 5};
    std::vector<int> myVec{6, 7, 8, 9, 10};
    print(myList.cbegin(), myList.cend());
    print(myVec.cbegin(), myVec.cend());
}

the following link might also be of interest - it checks the type of iterator given the container:
http://www.cplusplus.com/forum/general/213171/
Thanks.
To print a space after every item except the final one, with any (input) iterator:

1
2
3
4
5
6
7
8
9
10
11
template <class Iter>
void print(Iter first, Iter  limit)
{

    while (first != limit ) {

        std::cout << *first ;
        ++first; // first, move the iterator forward
        if( first != limit ) std::cout << ' ' ; // print a space if there is a next element
    }
}
Last edited on
Topic archived. No new replies allowed.