Using vector :: erase for the entire range

there is

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

As fast as

 v.clear(); 

?

I do not need small overheads, such as additional function calls, etc., the compiler will embed this material.

I ask because I have code like the following:

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

last_it will usually be the final iterator, but not always. I know that erasing a vector does not have value from the end, because subsequent elements in the vector will need to be copied. In the case where last_it is not the final iterator (rarely), I can handle this. But I do not want to introduce such an overhead when I basically want to clear the vector. So I decided to write my code as follows:

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

I would like to know if this is necessary in order to avoid the penalty for erasing the entire vector. I would prefer my code to be clean and use a single line statement if there is no penalty.

+8
c ++ vector
source share
3 answers

A look into the source code of the vector (link to visual studio 2012 (code snippet below) or SGI (line 434)), clear is defined as:

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

So I think so.

So in your case, I would not use the if statement, but simply:

 v.erase(v.begin(), last_it); 
+8
source share

Do not worry about this and write the obvious code using erase . If you delete to the end, there will be no items left to move down, so there should be a minimal performance difference between them, if any.

+8
source share

The problem is that there is not a single answer to your question, because there is no single implementation of the standard C ++ library, which is used on all platforms. The only thing specified in the standard is the algorithmic complexity of a clear operation. In particular, it can be a constant time for trivially destructible types; for types requiring destruction, it will be linear in the number of destruction. This is the only guarantee you get from the C ++ standard.

The standard library is usually distributed as part of your compiler installation, so implementation details such as this can be very different from compiler to compiler. If you are interested in only one version of the compiler, you can find the answer, but find out that it can change if you ever change platforms.

+1
source share

All Articles