I am iterating through a bidirectional data structure. I can do it either by using (++
, --
) or (std::prev
,std::next
,std::advance
). Is there a advantage of using later over the other?
They slightly do different things. So neither is better in general.
In particular std::prev
doesn't modify itr
. So, it is better when itr
shouldn't or couldn't (see S.M.'s answer for example of latter) be modified. --itr
and std::advance
do modify itr
, so they are better when itr
must be modified.
An advantage of std::prev
and std::advance
over --itr
is their argument n
which allows avoiding writing a loop when you need to advance multiple steps. They're more efficient than a loop if the iterator is random access.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With