I have an std::vector
, and I want a separate std::vector
containing only the last n elements of the original vector. Besides a loop over the entire vector inserting one-by-one, is there a cleaner way of doing this?
If you want to access the last element of your vector use vec. back() , which returns a reference (and not iterator). Do note however that if the vector is empty, this will lead to an undefined behavior; most likely a crash.
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
.
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