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

2022-01-10 00:00:00 iterator c++ 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)

相关文章