【发布时间】:2020-10-05 16:55:08
【问题描述】:
对于我的项目,我需要使循环中的迭代器转到容器中的下一个项目,执行一些操作,然后再次返回到同一个迭代器并继续,但是,由于某种原因,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);
}
}
【问题讨论】:
-
问题是the range-for statement 遍历容器中的values。在您的情况下,变量
it是容器中的 value ,而不是迭代器。并且没有办法从值中获取迭代器。如果您需要使用实际的迭代器,那么您应该使用实际的迭代器显式创建这样一个循环(“正常”for循环)。
标签: c++ for-loop c++11 iterator for-range