如何在不递增(递减)迭代器的情况下获取 std::list 中的下一个(上一个)元素? [英] How get next (previous) element in std::list without incrementing (decrementing) iterator?

查看:22
本文介绍了如何在不递增(递减)迭代器的情况下获取 std::list 中的下一个(上一个)元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个 std::list<int>lst 和一些 std::list<int>::iterator it 用于遍历列表.并取决于 it 我想在我的代码中使用 it + 1it - 1 的值.有没有像 next()prev() 这样的好方法(我在 stl 文档中找不到这样的东西)?还是我应该每次都复制 it 并增加(减少)副本?

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?

推荐答案

复制和递增/递减副本是唯一可行的方法.

Copying and incrementing/decrementing the copy is the only way it can be done.

您可以编写包装函数来隐藏它(正如答案中提到的,C++11 有 std::prev/std::next 可以做到这一点(并且 Boost 定义了类似的函数).但它们是围绕这个的包装器复制和递增"操作,因此您不必担心自己做错了.

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".

这篇关于如何在不递增(递减)迭代器的情况下获取 std::list 中的下一个(上一个)元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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