简体   繁体   中英

Initializing an iterator to a position within a vector

I am trying to initialize a vector<string>::iterator it to a position x in my vector. It seems I can only position my iterator to the first element of the vector thanks to it=vector.begin(); .

What if I want the iterator to start working from the position x? How can I move it? I don't want my iterator to go through the whole vector when I already know I can find what I'm looking for starting from the position x.

I tried initializing the iterator as it=vector.begin() and then moving it to x with advance(it,x); but it's not working. If I try to print *it it won't return any value.

How can I solve this?

A std::vector support random access iterators, this means that you can directly add a specified amount to an iterator, eg

auto it = vector.begin() + 4;

In any case std::advance should definitely work:

auto it = vector.begin();
std::advance(it, 4);

And also std::next if you don't want to modify an existing iterator:

auto it = std::next(vector.begin(), 4);

If you know the exact position, you can use it + x . Other approach is to use advance() as you write in the question. The following does work :

std::vector<int> a{10,20,30,40};
auto it1 = a.begin() + 2;
auto it2 = a.begin();
advance(it2, 2);
cout << *it1 << " " << *it2;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM