Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can the iterator be shared between vectors in C++?

In c++, if I have two arrays a[10] and b[10], I can introduce an index i can be used for both arrays points to the (i+1)-th element, a[i] and b[i]. Is the iterator can be shared as well or I need to do something like:

vector<int> a;
vector<int> b;    //assume both are initiated and same
vector<int>::iterator i;    //assume program know i=10 and *i=20 in vector a 
vector<int>::iterator j = b.begin();

for(;j != b.end();j++){
    if(*j == *i){
        break;
    }
}

and then I get the iterator j which points to the same position but in vector b? Can I simply know the position of i in a and then j=b.begin()+pos(i)

like image 523
lolibility Avatar asked Mar 23 '23 07:03

lolibility


1 Answers

Iterators in the Standard C++ Library are modeled after pointers, not after indexes. In the same way that pointers cannot be shared among multiple arrays, iterators cannot be shared among vectors or other collections.

If you need to iterate multiple vectors in parallel, you can use indexes rather than iterators. If you need to find the position of an iterator, you can use std::distance like this:

std::distance(b.begin(), my_iter)

If you need to move an iterator i in vector a to the same position as iterator j in vector b, you can do this:

auto i = a.begin();
// j is an iterator in vector "b"
advance(i, distance(b.begin(), j));
like image 118
Sergey Kalinichenko Avatar answered Apr 20 '23 18:04

Sergey Kalinichenko