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

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

本文关键字:元素 另一个 集中 C++ 迭代器 何使      更新时间:2023-10-16

相同类型的集合有两个迭代器:

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

在几个步骤之后,i1指向f1的某个元素,该元素具有index=index1(这可能是未知的)。我需要将第二迭代器i2设置为索引等于index1…的f2元素

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

使用std::advance作为:

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

完成!

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

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

:-)


请注意,std::advance返回void,因此不能编写以下内容:

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

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

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

因此,为了便于使用,在C++11:中添加了std::next

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

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

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

希望能有所帮助。

我不清楚你的索引是什么,但如果你已经移动了i1,你可以使用std::distance来查看移动了多少,然后使用std::advance

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

使用std::advance(i2,index1)推进i2

相关文章: