检查迭代器中的倒数第二位 [英] check if second to last in an iterator

查看:181
本文介绍了检查迭代器中的倒数第二位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种干净的方法来检查我目前是否处于C ++迭代中的倒数第二个元素?如:

Is there a clean way to check if I am currently at the second to last element in an iteration in C++? As in:

for (vector::iterator it = v.begin(); it < v.end(); ++it)
{
   if (it points to second to last element)
      cout << "at second to last";
}


推荐答案

最简单的方法是比较你的迭代器与确实指向倒数第二个的迭代器。一个简单的方法是:

The easiest way would be to compare your iterator against one which does indeed point to the second-to-last. And an easy way to get that is:

vector::iterator secondLast = v.end() - 2;

当然假设 v.size()> = 2 。但上面没有概括为其他容器类型,你可以这样做:

Assuming of course that v.size() >= 2. But the above doesn't generalize to other container types, for which you could do this:

vector::iterator secondLast = (++v.rbegin()).base();

这应该从最后一个元素回退一步,然后转换为常规(前向)迭代器。这将适用于其他容器类型,如列表。

This should rewind from the last element one step, then convert to a regular (forward) iterator. This will work with other container types like lists.

或者对于一般解决方案可能更清楚:

Or perhaps clearer for the general solution:

vector::iterator secondLast = v.end();
std::advance(secondLast, -2);

同样需要2的大小和随机访问或双向类型的迭代器。

Again this requires size of 2 and iterators of random access or bidirectional type.

最后,一个C ++ 11解决方案:

And finally, a C++11 solution:

auto secondLast = std::prev(v.end(), 2);

这篇关于检查迭代器中的倒数第二位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆