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

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

问题描述

说我有一个std::list<int> lst和一些std::list<int>::iterator it用于遍历列表.并取决于我想在代码中使用it + 1it - 1it的值.有没有什么好办法做到这一点,例如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天全站免登陆