Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a set of type set<int> and I want to get an iterator to someplace that is not the beginning.

I am doing the following:

set<int>::iterator it = myset.begin() + 5;

I am curious why this is not working and what is the correct way to get an iterator to where I want it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
140 views
Welcome To Ask or Share your Answers For Others

1 Answer

myset.begin() + 5; only works for random access iterators, which the iterators from std::set are not.

For input iterators, there's the function std::advance:

set<int>::iterator it = myset.begin();
std::advance(it, 5); // now it is advanced by five

In C++11, there's also std::next which is similar but doesn't change its argument:

auto it = std::next(myset.begin(), 5);

std::next requires a forward iterator. But since std::set<int>::iterator is a bidirectional iterator, both advance and next will work.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...