MelMed
MelMed

Reputation: 255

Difference between two features of vector

What would be the difference between:

std::vector::erase

and

std::vector::clear

What I want to do is to get rid of all elements, positions, including memory addresses and having no exception thrown.

vector<array<double,1000>> S1(1000);

I would like at the end to get rid of the 1000*2 created memory addresses.

Upvotes: 2

Views: 232

Answers (5)

sunrise
sunrise

Reputation: 1

v.erase(v.begin(),v.end()) is equivalent to v.clear() where v is an object of any vector. Here clear will be used for delete all the vector elements but erase can we used to delete any specific element or range of element.

Upvotes: 0

juanchopanza
juanchopanza

Reputation: 227370

The only sure way to release the memory that I can think of is to swap with a temporary vector:

vector<array<double,1000>> S1(1000);
...
vector<array<double,1000>>().swap(S1);

Although this might look strange at first, it is a known, widely used idiom.

In C++11, moving from the original vector might be an option, although it is not guaranteed to clear the memory or even clear the vector (I cannot think of a reason why an implementation wouldn't do that though):

{
  vector<array<double,1000>> tmp(std::move(S1));
} // tmp dies on exiting scope, memory is cleared

Altenratively, a call to std::vector::shrink_to_fit could result in memory de-allocation, but there are no guarantees:

S1.clear();
S1.shrink_to_fit();

Upvotes: 2

Ralph Tandetzky
Ralph Tandetzky

Reputation: 23600

The function clear() empties the vector. The function erase() removes selective elements (there are several overloads). erase(v.begin(), v.end()); is equivalent to calling clear();. The created memory will still be reserved for possible future use. If you want to be sure to free all this memory, then call v.clear(); and then v.shrink_to_fit(), if you have a C++11 compiler. (There's no actual guarantee that the memory will be freed, it's just a request, but I don't know of any compiler which doesn't free the memory.) If you don't have C++11 compliance then use the alternative std::vector<std::array<double,1000>>().swap(v);. That's called the shrink to fit idiom.

Upvotes: 0

Denis
Denis

Reputation: 175

Erase lets you specify begin and end positions whereas clear clears the whole Vector.

http://www.cplusplus.com/reference/vector/vector/erase/

http://www.cplusplus.com/reference/vector/vector/clear/

Upvotes: 0

Benjamin Lindley
Benjamin Lindley

Reputation: 103693

erase gets rid of elements selectively by position. clear gets rid of all elements unconditionally, and can be considered syntactic sugar for a call to v.erase(v.begin(),v.end());

Upvotes: 4

Related Questions