Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

vector

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.

like image 525
Brett Avatar asked Feb 01 '14 02:02

Brett


People also ask

How do you delete a first N element from a vector?

Use the . erase() method: // Remove the first N elements, and shift everything else down by N indices myvec.

How do you remove a specific element from a vector in C++?

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.

How do you remove the first element of a vector in C++?

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.

How do I remove an element from a std::vector?

vector::clear() clear() function is used to remove all the elements of the vector container, thus making it size 0.


1 Answers

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 
like image 82
Moritz Avatar answered Sep 28 '22 10:09

Moritz