C++ 如何在不递增(递减)迭代器的情况下获取 std::list 中的下一个(上一个)元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10137214/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How get next (previous) element in std::list without incrementing (decrementing) iterator?
提问by Mihran Hovsepyan
Say I have an std::list<int> lst
and some std::list<int>::iterator it
for iterating through the list. And depended to value of the it
I want to use it + 1
or it - 1
in my code. Is there some good way to do that like next()
, prev()
(I couldn't find such things in stl documentation)? Or should I copy the it
each time and increment(decrement) the copy?
假设我有一个std::list<int> lst
和一些std::list<int>::iterator it
用于遍历列表。并取决于it
我想使用it + 1
或it - 1
在我的代码中的价值。有没有什么好的方法可以做到这一点next()
,prev()
(我在 stl 文档中找不到这样的东西)?或者我应该it
每次复制并增加(减少)副本?
采纳答案by jalf
Copying and incrementing/decrementing the copy is the only way it can be done.
复制和递增/递减副本是唯一可以完成的方法。
You can write wrapper functions to hide it (and as mentioned in answers, C++11 has std::prev/std::next which do just that (and Boost defines similar functions). But they are wrappers around this "copy and increment" operation, so you don't have to worry that you're doing it "wrong".
您可以编写包装函数来隐藏它(正如答案中提到的,C++11 有 std::prev/std::next 可以做到这一点(并且 Boost 定义了类似的函数)。但它们是围绕这个“复制和increment”操作,所以你不必担心你做错了。
回答by Stephan Dollberg
Yes, since C++11 there are the two methods you are looking for called std::prev
and std::next
. You can find them in the iterator library.
是的,从 C++11 开始,您正在寻找两种方法,称为std::prev
和std::next
。您可以在迭代器库中找到它们。
Example from cppreference.com
来自 cppreference.com 的示例
#include <iostream>
#include <iterator>
#include <vector>
int main()
{
std::list<int> v{ 3, 1, 4 };
auto it = v.begin();
auto nx = std::next(it, 2);
std::cout << *it << ' ' << *nx << '\n';
}
Output:
输出:
3 4
回答by Benjamin Bannier
A simple precanned solution are prior
and next
from Boost.utility
. They take advantage of operator--
and operator++
but don't require you to create a temporary.
一个简单的预装解决方案是prior
和next
来自Boost.utility
。他们利用operator--
和operator++
,但不要求你创建一个临时的。