Keeping the first N elements of a std::vector<> and removing the rest

c++, vector

Solution

Yes, you can use `std::vector::resize`, which just truncates if the length of the vector is greater than n.

See here: http://www.cplusplus.com/reference/vector/vector/resize/

std::vector<int> myvector;

for (int i=1;i<1000;i++) myvector.push_back(i);

myvector.resize(50);
// myvector will contain values 1..50

Problem

I have a `std::vector<int>` variable in my `C++` application. The size of the vector is determined at runtime, but is typically about `1000`. I have sorted this vector (which works well), and after sorting, I would like to keep only the first `50` elements. I have tried: ``` kpts.erase(kpts.begin() + 50, kpts.end()); ``` where `kpts` is my vector, and the performance is horrible! Presumably because of the way `erase` operates. Is there a way to only keep the first `50` elements of a vector? It seems like it should be obvious, but I can't find a way to do this.

Original source