5

There is a set visited. And I wanna check all its elements from 4-th to last. I'm trying to do something like that

int visited_pointer = 4;
for ( set<int>::iterator i_visited=visited.begin()+visited_pointer
    ; i_visited!=visited.end()
    ; i_visited++
)

and got errors with operator+.

How can I do that in the right way?

2 Answers 2

13

That usage of operator+ is only provided for random-access iterators. set iterators are bi-directional iterators.

But the function std::advance can be used to move any iterator a certain number of places:

#include <iterator>

//...

set<int>::iterator i_visited = visited.begin();
for ( std::advance(i_visited, visited_pointer)
    ; i_visited!=visited.end()
    ; ++i_visited
)
0
2

sets do not support random access iterators (i.e. ones that support adding values to an iterator), so the only way to do this is to iterate through the first (whatever that may mean) four members until you get to the one you want. It sounds to me like set is not the right container for whatever it is you are trying to do.

2
  • Re: "whatever that may mean": a set is an ordered container, and the first member is the one that comes first according to that ordering. May 1, 2011 at 17:20
  • @Mike True. I must admit I'm accustomed to thinking of sets as being like smalltalk "bags", with no order and the set's ordering function only being used to guarantee uniqueness. But that's just me.
    – user2100815
    May 1, 2011 at 17:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.