如何使迭代器指向与C++集中的另一个元素相同的元素
How to make an iterator point to the same element as another one in a C++ set?
相同类型的集合有两个迭代器:
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
。
相关文章:
- 使用std::transform将一个范围的元素添加到另一个范围中
- 检查 2D 网格的某个元素是否与另一个元素共享对角线、水平线或垂直线
- 为什么在 std::map 上移动无法将元素从一个映射移动到另一个映射
- 如何从一个容器中获取某些元素并将其转换插入到另一个容器中?
- 如何从另一个向量中的另一个第一元素减去向量中的第一元素
- 保留从一个多集复制到另一个多集的元素的顺序
- 如何从一个向量中删除最小元素并添加到另一个向量,而第一个变为空?
- C++:检查向量中的元素是否大于另一个具有相同索引的元素的有效方法?
- 从另一个向量中搜索和找到元素的有效方法
- 如果在C 中已经回荡了另一个相同值的阵列元素,请防止循环回荡
- 当我尝试将一个向量元素的值分配给另一个向量元素时,为什么我的应用程序会崩溃
- 如何将元素添加到从另一个线程绑定到 XAML 的 IVector
- 使用对另一个元组不同类型的元素的非常量引用来初始化元组的元素
- 并行算法将向量的元素分配到另一个元素的元素
- C 初始化矢量每个元素,带有另一个向量的参数
- 模板函数,它使用 n_copy 复制前 n 个元素形成一个向量,另一个向量导致编译错误
- 递增迭代器以指向另一个迭代器的下一个元素
- 如何转换一个类方法以修改另一个类的私有元素?
- 将映射从第二个元素复制到另一个地图
- 使用擦除-删除范例将元素从一个向量移动到另一个向量