How to get a vector containing only the last n elements of another vector?

int n = 5;
std::vector<int> x = ...;
std::vector<int> y(x.end() - n, x.end())

Of course this will crash and burn if x.size() < n

To elaborate a little, std::vector (like most of the standard library containers) has a constructor which takes a pair of iterators. It fills the vector with all the items from the first iterator up to the second.


You can construct copyVector directly using the two iterator constructor:

std::vector<int> original = ...;
std::vector<int>::iterator start = std::next(original.begin(), M);
std::vector<int> copyVector(start, original.end());

or use std::vector's assign method:

std::vector<int>::iterator start = std::next(original.begin(), M);
std::vector<int> copyVector = ... ;
...
copyVector.assign(start, original.end());

where M is calculated from original.size() and n.

Tags:

C++