Reputation: 2912
Which operation is most costly in C++?
1. Resize of a vector (decrease size by 1)
2. Remove last element in vector
Upvotes: 1
Views: 1313
Reputation: 310960
In my opinion they are equivalent. The both operations remove the last element and decrease the size.:)
According to the C++ Standard
void resize(size_type sz); 12 Effects: If sz <= size(), equivalent to calling pop_back() size() - sz times
So they are simply equivalent according to my opinion and the point of view of the Standard.:)
Also if to consider member function erase
instead of pop_back
(in fact they do the same in this case) then according to the same Standard
4 Complexity: The destructor of T is called the number of times equal to the number of the elements erased, but the move assignment operator of T is called the number of times equal to the number of elements in the vector after the erased elements.
As there are no move operations for the last element then the cost is the same.
Upvotes: 0
Reputation: 70526
From http://en.cppreference.com/w/cpp/container/vector which essentially quotes the Standard:
void pop_back();
Removes the last element of the container. No iterators or references except for
back()
andend()
are invalidated.
void resize( size_type count );
Resizes the container to contain count elements. If the current size is greater than count, the container is reduced to its first count elements as if by repeatedly calling
pop_back()
.
So in this case, calling resize(size() - 1)
should be equivalent to calling pop_back()
. However, calling pop_back()
is the right thing to do as it expresses your intent.
NOTE: the answer is reflecting the changed interface of C++11's std::vector::resize()
, which used to contain a hidden default argument which was being copied around (and which may or may not have been optimized away).
Upvotes: 11