Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using vector::erase for the whole range

Tags:

c++

vector

Is

v.erase(v.begin(), v.end());

Just as fast as

v.clear();

?

I don't care about little overheads such as extra function calls etc, the compiler will inline that stuff.

The reason I ask is because I have code like the following:

v.erase(v.begin(), last_it);

last_it will usually be the end iterator, but not always. I know that erasing a vector not from the end has a cost, because later elements in the vector will need to be copied down. In the case where last_it is not the end iterator (rare), I can live with that. But I don't want to introduce such overhead when I basically want to clear the vector. So I considered writing my code like this:

if (last_it == v.end())
{
    v.clear();
}
else
{
    v.erase(v.begin(), last_it);
}

I would like to know whether this is necessary to avoid a performance penalty for erasing the whole vector. I would prefer to keep my code clear and use a single-line statement if there is no penalty.

like image 981
Neil Kirk Avatar asked Sep 19 '13 14:09

Neil Kirk


People also ask

How do you delete a range of elements in a vector?

All the elements of the vector are removed using clear() function. erase() function, on the other hand, is used to remove specific elements from the container or a range of elements from the container, thus reducing its size by the number of elements removed.

Which function in vector will allow to delete a range of values?

Using erase(const_iterator first, const_iterator last) function. That's all about removing a range of elements from a vector in C++.

Does vector erase change capacity?

No. That's implied by the fact that iterators, pointers and references prior to the point of erase remain valid. Reducing the capacity would require a reallocation.


2 Answers

Don't worry about this and write the obvious code using erase. If you erase to the end there won't be any elements left to shift down so there should be minimal performance difference between the two, if any.

like image 160
Mark B Avatar answered Nov 14 '22 00:11

Mark B


Looking into the sourcecode of vector (refering to visual studio 2012 (code snippet below) or SGI (line 434) one), clear is defined as:

void clear() _NOEXCEPT
{   // erase all elements
    erase(begin(), end());
}

So i guess yes.

So in your case, I wouldn't use the if statement, and just do:

v.erase(v.begin(), last_it);
like image 26
user1810087 Avatar answered Nov 14 '22 00:11

user1810087