开发者

access to nth element of set

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()+vis开发者_StackOverflow中文版ited_pointer
    ; i_visited!=visited.end()
    ; i_visited++
)

and got errors with operator+.

How can I do that in the right way?


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
)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜