我的问题如下:我使用迭代器,我想将每个元素与下一个元素进行比较。原型(prototype)如下所示,如何增加迭代器才能进行比较? 另外,我怎样才能为这种情况设置适当的条件?我的意思是如何指向最后一个元素,而不是像 end() 函数那样指向最后一个元素之后的下一个元素:
std::vector<T>::const_iterator it;
std::vector<T>::const_iterator it2;
for (it = set.begin(), it != set.end(); it++)
{
// some things happen
if ( final == it )
{
if ( it != set.end()-1 ) // how to write properly condition?
{
it2 = it + 1; //how to assign the next here?
if (...)//some condition
{
if ( it->func1() - it2->func1()) < 20 ) //actual comparison of two consecutive element values
// do something
}
}
}
}
最佳答案
在 C++11 中使用函数 std::next()和 std::prev() .
您的代码可能会变成:
// before
it != std::set.end()-1
// after
it != std::prev(set.end())
和
// before
it2 = it + 1;
// after
it2 = std::next(it);
对于非 vector 容器也是如此,例如 map、set 或其他容器。
注意:在 std::next(it)
之后,“it”迭代器保持不变!
注意 2:使用 it2 = std::next(it,n);
根据需要递增。
关于c++ - 递增迭代器 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14832971/