Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which one is better std::prev(itr) or --itr?

Tags:

c++

iterator

stl

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?

like image 452
Sumit Jha Avatar asked Apr 10 '18 14:04

Sumit Jha


1 Answers

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.

like image 81
eerorika Avatar answered Sep 20 '22 11:09

eerorika