How do I create a new list from an existing list using the first n-5 elements?
How do I create a new std :: list from an existing std :: list, taking the first n-5 elements? n - size of the existing list (list)
+3
PaolaJ.
source
to share
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
Steve jessop
source
to share