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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 13:39:41  来源:igfitidea点击:

How get next (previous) element in std::list without incrementing (decrementing) iterator?

c++listiterator

提问by Mihran Hovsepyan

Say I have an std::list<int> lstand some std::list<int>::iterator itfor iterating through the list. And depended to value of the itI want to use it + 1or it - 1in 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 iteach time and increment(decrement) the copy?

假设我有一个std::list<int> lst和一些std::list<int>::iterator it用于遍历列表。并取决于it我想使用it + 1it - 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::prevand std::next. You can find them in the iterator library.

是的,从 C++11 开始,您正在寻找两种方法,称为std::prevstd::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 priorand nextfrom Boost.utility. They take advantage of operator--and operator++but don't require you to create a temporary.

一个简单的预装解决方案是priornext来自Boost.utility。他们利用operator--operator++,但不要求你创建一个临时的。