简体   繁体   中英

Time Complexity of std::vector::erase

I've found a way to remove an element from an STL vector my its value here :

vec.erase(remove(vec.begin(), vec.end(), value), vec.end());

Now I'd like to know how efficient this method is, meaning its time complexity in Big O notation.

vec.erase(remove(vec.begin(), vec.end(), value), vec.end());

In this case remove compacts the elements that differ from the value to be removed (value) in the beginning of the vector and returns the iterator to the first element after that range. Then erase removes the elements.

So this makes this operation O(n).

The C++11 standard specifies in [vector.modifiers]/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.

In particular, erasing elements at the end is quite cheap since all that is done is destroying the elements to be erased, so the time complexity of the erase -call should be linear in terms of the number of occurrences of value inside vec - which corresponds to Θ(n) in Big-Oh-Notation. The complexity of the whole expression is still linear since remove has linear complexity in terms of the length of the range it is applied to. If the size of vec is described by the variable m we have Θ(n + m) for the complete expression which equals O(m) (since n < m and m + n < 2m , O(2m) = O(m) )

It could be anything as the complexity of the destructures is unknown

But assuming it is constant then it will be O(n)

O(N),因为您正在遍历向量的每个元素。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM