How get next (previous) element in std::list without incrementing (decrementing) iterator?(如何在不递增(递减)迭代器的情况下获取 std::list 中的下一个(上一个)元素?)
问题描述
假设我有一个 std::list<int>lst 和一些 std::list<int>::iterator it 用于遍历列表.并取决于 it 我想在我的代码中使用 it + 1 或 it - 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 中的下一个(上一个)元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在不递增(递减)迭代器的情况下获取 std::list 中的下一个(上一个)元素?
基础教程推荐
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- CString 到 char* 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 初始化列表*参数*评估顺序 2021-01-01
