How do I create a new list from an existing list using the first n-5 elements?
1 answer
std::list<T> newlist(oldlist.begin(), std::prev(oldlist.end(), 5));
where T
is the value type of the old list.
std::prev
is new in C ++ 11, but if you don't have it, you can use std::advance
instead:
std::list<T>::const_iterator end = oldlist.end();
std::advance(end, -5);
std::list<T> newlist(oldlist.begin(), end);
In any case, it is your responsibility to provide oldlist.size() >= 5
. Neither std::prev
, nor std::advance
does it for you.
+7
source to share