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?
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- how to split a list into a given number of sub-lis
- thread_local variables initialization
相关文章
- List可以存储接口类型的数据吗?
-
C# List
.FindAll 时 空指针异常 - Class layout in C++: Why are members sometimes ord
- What is the complexity of bisect algorithm?
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Given a list and a bitmask, how do I return the va
Yes, since C++11 there are the two methods you are looking for called
std::prev
andstd::next
. You can find them in the iterator library.Example from cppreference.com
Output:
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".
A simple precanned solution are
prior
andnext
fromBoost.utility
. They take advantage ofoperator--
andoperator++
but don't require you to create a temporary.