Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove element(s) from std::vector without resizing it

Tags:

c++

stl

iterator erase ( iterator position );

iterator erase ( iterator first, iterator last );

Erase elements Removes from the vector container either a single element (position) or a range of elements ([first,last)).

This effectively reduces the vector size by the number of elements removed, calling each element's destructor before.

and:

remove

Removes all elements equaling the given value value from the range, defined by [first, last). Removing is done by shifting the elements in the range in such a way that required elements are overwritten. The elements between the old and the new ends of the range are left intact. Iterator to the new end of the range is returned.

Is there any way to remove elements from a std::vector within an iterator range(something like remove, but ALL elements from [first, last]) without resizing the vector? I need to keep it's maximum size that it reached at runtime to prevent reallocs.

Thanks!

like image 653
Mircea Ispas Avatar asked Mar 31 '11 07:03

Mircea Ispas


People also ask

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

vector::erase() erase() function is used to remove elements from a container from the specified position or range.

How do you remove an element from a value in vector?

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.

How do you remove a random element from a vector?

The idea is to swap the last element and an element you want to remove and then pop_back() . If you need to remove the last elemtent - just pop_back() . The order of the vector will not be the same but you get a fast remove method.

How do you remove an object from a vector?

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.


1 Answers

resize will never reduce the capacity of the vector - you can safely use erase for this.

Use reserve to make a vector preallocate space for a certain number of items. Unless you actually exceed this limit, no insert or erase or resize will lead to a realloc. If you exceed it, the vector will internally reserve more space - but it will not reduce the internal capacity.

like image 68
Erik Avatar answered Oct 13 '22 03:10

Erik