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.
Use the . erase() method: // Remove the first N elements, and shift everything else down by N indices myvec.
The C++ vector has many member functions. Two of these member functions are erase() and pop_back(). pop_back() removes the last element from the vector. In order to remove all the elements from the vector, using pop_back(), the pop_back() function has to be repeated the number of times there are elements.
To remove first element of a vector, you can use erase() function. Pass iterator to first element of the vector as argument to erase() function.
vector::clear() clear() function is used to remove all the elements of the vector container, thus making it size 0.
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
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