3

对于我的项目,我需要使循环中的迭代器转到容器中的下一个项目,执行一些操作,然后再次返回到同一个迭代器并继续,但是,由于某种原因既不是advance也不是next,然后使用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);
        }

}
4

1 回答 1

6

基于范围的 for 循环迭代元素。这个名字it在这里令人困惑;它不是迭代器而是元素,这就是为什么std::next不要std::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);
}
于 2020-06-16T06:50:30.977 回答