在STL容器中偷看下一个元素 [英] Peek the next element in STL container

查看:122
本文介绍了在STL容器中偷看下一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在迭代器当前指向的容器中查看下一个元素而不改变迭代器?

is it possible to peek next element in a container which the iterator currently points to without changing the iterator?

例如在std :: set中,

For example in std::set,

int myArray[]= {1,2,3,4};
set <int> mySet(myArray, myArray+4);
set <int>::iterator iter = mySet.begin();

//peek the next element in set without changing iterator.

mySet.erase(iter); //erase the element if next element is n+1


推荐答案

不与迭代器一般。迭代器不能保证能够非破坏性地操作。经典的例子是一个Input Iterator,它实际上代表了一个基本的输入流。

Not with iterators in general. An iterator isn't guaranteed to be able to operate non-destructively. The classic example is an Input Iterator that actually represents an underlying input stream.

但是有一些东西适用于这种迭代器。 Forward Iterator 不会通过向前移动集合的行为使之前的副本自动失效。大多数迭代器(包括用于STL集合的迭代器)至少是前向迭代器,如果不是更多功能的版本,则只有输入迭代器或输出迭代器更受限制。因此,您可以简单地制作一个迭代器的副本,增加副本并检查 ,然后返回到原始迭代器。

There's something that works for this kind of iterator, though. A Forward Iterator doesn't invalidate previous copies of itself by the act of moving forward through the collection. Most iterators (including those for STL collections) are at least Forward Iterators, if not a more functional version- only Input Iterators or Output Iterators are more restricted. So you can simply make a copy of your iterator, increment the copy and check that, then go back to your original iterator.

peek代码:

set <int>::iterator dupe = iter;
++dupe;
// (do stuff with dupe)

这篇关于在STL容器中偷看下一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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