如何在循环中访问list前后元素

本文介绍了在C++中如何访问std::list容器中当前迭代器前后的元素,包括复制整个列表、使用C++11中的std::prev和std::next函数、使用Boost库中的prior和next函数以及直接创建新的迭代器等方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 复制整个list

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

2. 使用C++0x或者C++11中的 pre 和 next

In C++0x, this functionality is neatly wrapped up in the std::prev function, which your C++ Standard Library implementation may support. If not, it looks something like this:

template <typename BidiIt> BidiIt prev(BidiIt x, typename std::iterator_traits<BidiIt>::difference_type n=1) { std::advance(x, -n); return x; }

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

Example from 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

3. 使用Boost中的 prior 和 next

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.

4. 创建新的iterator

std::list is only bidirecitonally iterable, so you can only move the iterator one position at a time. You thus need to create a new iterator:

iter_copy = iter; --iter;

Obviously, you are responsible for ensuring that a previous element actually exists before you decrement the iterator.

 

Reference:

http://stackoverflow.com/questions/10137214/how-get-next-previous-element-in-stdlist-without-incrementing-decrementing

http://stackoverflow.com/questions/5586377/how-to-access-the-previous-element-in-a-c-list-iterator-loop

转载于:https://www.cnblogs.com/learnopencad/p/4300471.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值