查看 STL 容器中的下一个元素

Peeking the next element in STL container(查看 STL 容器中的下一个元素)
本文介绍了查看 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

推荐答案

一般不使用迭代器.不保证迭代器能够非破坏性地运行.经典的例子是一个实际代表底层输入流的输入迭代器.

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.

所以你的偷看代码:

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

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)