Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove several elements from the end of std::vector?

Let's say I have a std::vector of integers:

std::vector<int> v;

v contains 100 elements, and I want to remove the last 10 elements. I can think of this solution:

v.erase(v.end() - 10, v.end());

Anything better?

like image 509
user1387866 Avatar asked Dec 24 '15 11:12

user1387866


People also ask

How do I remove multiple elements from a vector in C++?

If you need to remove multiple elements from the vector, the std::remove will copy each, not removed element only once to its final location, while the vector::erase approach would move all of the elements from the position to the end multiple times.

How do you remove an element from the end of a vector?

The standard solution to remove an element from a vector is with the std::vector::erase function. It takes an iterator to the position where the element needs to be deleted. To delete an element at the end of a vector, pass an iterator pointing to the last element in the vector.

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

The erase() function can remove an element from the beginning, within, or end of the vector. In order to remove all the elements from the vector, using erase(), the erase() function has to be repeated the number of times there are elements, beginning from the first element.

How do I erase an element from std::vector <> by value?

You need to use std::remove algorithm to move the element to be erased to the end of the vector and then use erase function. Something like: myVector. erase(std::remove(myVector. begin(), myVector.


1 Answers

You may try this:

v.resize(v.size()-10);

However, you need to benchmark it against your method. I am not sure it is better or even it may be exactly the same.

You may also check the size before resizing:

if(v.size()>=10){
    v.resize(v.size()-10);
}

EDIT:

Resize removes elements at the end of the vectors: http://www.cplusplus.com/reference/vector/vector/resize/

If n is smaller than the current container size, the content is reduced to its first n elements, removing those beyond (and destroying them).

like image 198
Humam Helfawi Avatar answered Oct 01 '22 10:10

Humam Helfawi