如何在不递增(递减)迭代器的情况下获取 std::list 中的下一个(上一个)元素?

2022-01-10 00:00:00 list iterator c++

假设我有一个 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".

相关文章