Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to traverse fixed number of elements in c++ list

Tags:

c++

stl

I want to traverse a list in C++ but only till fifth from last not till the end. But I see that there is no "-" operator defined so that I could use

list<>::iterator j=i-5;

I can do it using size() function somehow keeping counts etc but is there any other direct way?

like image 745
tariq zafar Avatar asked Dec 11 '22 08:12

tariq zafar


2 Answers

Count is the only practical way that may not involve effectively traversing the list in some way.

auto myEnd = std::advance(myList.end(),-5)

but this will just traverse the last five list elements to get to your desired point, so its no faster or more elegant than most other solutions. However, using an integer loop does require keeping both an integer count and an iterator, this really only requires the iterator so in that regard it may be nicer.

If your <list> has an O(1) count, and the distance back from end is large, use an integer loop, else the above is nice.

like image 83
RichardPlunkett Avatar answered Dec 27 '22 21:12

RichardPlunkett


List doesn't support random access iterators. You can use reverse iterator and counter.

like image 30
son of the northern darkness Avatar answered Dec 27 '22 21:12

son of the northern darkness