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

c++, iterator, set

Solution

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.

Problem

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?

Original source

Related problems