如何使迭代器指向与C++集中的另一个元素相同的元素?

jus*_*tik 3 c++ iterator set

对于相同类型的集合,有2个迭代器:

    typename TFunction <T>::Type ::const_iterator i1 = f1.begin();
    typename TFunction <T>::Type ::const_iterator i2 = f2.begin();
Run Code Online (Sandbox Code Playgroud)

在几个步骤之后,i1指向具有index = index1的f1的一些元素(可能不知道).我需要将第二个迭代器i2设置为具有与index1相同索引的f2元素...

这可以在没有将i1转换为索引的情况下完成吗?

Naw*_*waz 5

使用std::advance如:

std::advance(it2, index1); //increments it2 index1 times!
Run Code Online (Sandbox Code Playgroud)

完成!

如果你不知道它的值index1,那么你总是可以使用当前的 计算它it1:

auto index1 = std::distance(f1.begin(), it1);
Run Code Online (Sandbox Code Playgroud)

:-)


注意std::advance返回void所以你不能写这个:

fun(f2.begin(), std::advance(it2, index1)); //error
Run Code Online (Sandbox Code Playgroud)

相反,如果你必须这样写:

std::advance(it2, index1); //first advance
fun(f2.begin(), it2);        //then use it
Run Code Online (Sandbox Code Playgroud)

为了简化这种用法,std::next在C++ 11中添加:

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

顺便说一句,在C++ 11中,你可以使用auto而不是typename thingy:

auto it1 = f1.cbegin(); //cbegin() returns const_iterator
auto it2 = f2.cbegin(); //cbegin() returns const_iterator
Run Code Online (Sandbox Code Playgroud)

希望有所帮助.