Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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?

like image 935
zebra Avatar asked Jul 30 '12 16:07

zebra


People also ask

How do you use the last element of a vector?

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.


2 Answers

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.

like image 194
john Avatar answered Nov 15 '22 13:11

john


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.

like image 43
juanchopanza Avatar answered Nov 15 '22 14:11

juanchopanza