对于我的项目,我需要使循环中的迭代器转到容器中的下一个项目,进行一些操作,然后再次返回相同的迭代器,然后继续进行,但是由于某种原因,无论是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);
}
}
基于范围的for循环迭代元素。这里的名字it
很混乱;这不是迭代器,而是元素,这就是为什么std::next
并且std::prev
不使用它。
在范围内执行for循环。
用作与传统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);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句