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?
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.
List doesn't support random access iterators. You can use reverse iterator and counter.
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