转到基于范围的 for 循环中的下一个迭代器

Go to next iterator in range-based for loop

本文关键字:for 循环 迭代器 下一个 范围 于范围      更新时间:2023-10-16

对于我的项目,我需要从循环中制作迭代器以转到容器中的下一项,执行一些操作,然后再次返回到相同的迭代器并继续,但是,由于某种原因,advancenext,然后使用prev似乎都不起作用。那么我怎样才能获得下一个迭代器并返回到上一个迭代器呢?

我收到以下错误消息:

no matching function for call to 'next(int&)'
no type named 'difference_type' in 'struct std::iterator_traits<int>'

谢谢!

template<class T>
void insert_differences(T& container)
{
for(auto it : container){
// do some operations here
//advance(it,1);
it = next(it); 
// do some operations here 
//advance(it, -1);
it = prev(it);
}
}

基于范围的 for 循环对元素进行迭代。it的名字在这里令人困惑;它不是迭代器而是元素,这就是为什么std::nextstd::prev不使用它的原因。

在某个范围内执行 for 循环。

用作与传统 for 循环等效的更具可读性 对一系列值进行操作,例如容器中的所有元素。

你必须自己使用迭代器编写循环,比如

for(auto it = std::begin(container); it != std::end(container); it++){
// do some operations here
//advance(it,1);
it = next(it); 
// do some operations here 
//advance(it, -1);
it = prev(it);
}