Home > Enterprise >  How to reverse a std::list at a given position?
How to reverse a std::list at a given position?

Time:10-27

I am trying to figure out how to reverse for example,grades{1, 2, 3, 4, 5, 6} starting at the third element.

I know for lists we cannot do (grades.begin() 2) to obtain the position, but I'm not sure how to go about it. This is what I have so far, where I'm just reversing the entire list:

reverse(firstList.begin(), firstList.end());

I want it to be reverse so that the list becomes: grades{1, 2, 6, 5, 4, 3}

CodePudding user response:

I know for lists we cannot do (grades.begin() 2) to obtain the position, but [...]

You are right about this. Providing the flexibility of list.begin() pos means, it is cheap to do that. The std::list iterators(i.e. BidirectionalIterator) can not be randomly-accessed efficiently (i.e. it is expensive). Therefore, as per the conventional, it must be verbose.

You need to be explicit to iterate via its element. That means, you can make use of std::next from <iterator> header to provide the starting point for std::reverse.

#include <iterator> // std::next
#include <algorithm> // std::reverse

std::list<int> grades{ 1, 2, 3, 4, 5, 6 };
std::reverse(std::next(grades.begin(), 2), grades.end());
//           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Live Demo

  • Related