justik
justik

Reputation: 4255

How to make an iterator point to the same element as another one in a C++ set?

There are 2 iterators to the sets of the same type:

    typename TFunction <T>::Type ::const_iterator i1 = f1.begin();
    typename TFunction <T>::Type ::const_iterator i2 = f2.begin();

After several steps i1 points to some element of f1 having index = index1 (it may not be known). I need to set the second iterator i2 to the element of f2 having the equal index as index1...

Can this be done without a conversion of i1 to the index?

Upvotes: 4

Views: 1771

Answers (3)

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361352

Use std::advance as:

std::advance(it2, index1); //increments it2 index1 times!

Done!

If you dont know the value of index1, then you can always compute it using the current it1 as:

auto index1 = std::distance(f1.begin(), it1);

:-)


Note that std::advance returns void so you cannot write this:

fun(f2.begin(), std::advance(it2, index1)); //error

Instead if you have to write this:

std::advance(it2, index1); //first advance
fun(f2.begin(), it2);        //then use it

So to ease such usages, std::next is added in C++11:

fun(f2.begin(), std::next(f2.begin(), index1)); //ok, don't even need it2!

BTW, in C++11, you could use auto instead of typename thingy:

auto it1 = f1.cbegin(); //cbegin() returns const_iterator
auto it2 = f2.cbegin(); //cbegin() returns const_iterator

Hope that helps.

Upvotes: 7

doctorlove
doctorlove

Reputation: 19232

I'm not clear what your index is, but if you have moved i1 you can use std::distance to see how much by and then use std::advance

std::advance(i2, std::distance(f1.begin(), i1));

Upvotes: 1

Asha
Asha

Reputation: 11232

Use std::advance(i2,index1) to advance i2.

Upvotes: 0

Related Questions