A Vectors in C++ can resize itself when more elements are added. It also allows deletion of elements. A basic idea is to double the array whenever it becomes full. However the actual library implementation may be more complex. If we create a new double sized array whenever current array becomes full (or it is about to become full), and copy current elements to new double sized array, we get amortized time complexity as O(1). So a particular insert operation may be costly, but overall time complexity remains O(1). Please refer Analysis of Algorithm | Set 5 (Amortized Analysis Introduction) for proof. So time complexity of push_back() is O(1).
1 2 3 4 5 6
What is the time complexity of erase() in vector()?
Since erasing an element requires moving other elements (to ensure random access), time complexity of erase is O(1).
2 3 4 5
- vector::crend() & vector::crbegin() with example
- vector :: cbegin() and vector :: cend() in C++ STL
- vector::front() and vector::back() in C++ STL
- vector::empty() and vector::size() in C++ STL
- vector::push_back() and vector::pop_back() in C++ STL
- How does Duff's Device work?
- Does overloading work with Inheritance?
- vector::at() and vector::swap() in C++ STL
- vector::begin() and vector::end() in C++ STL
- Minimum number of days required to complete the work
- Vector in C++ STL
- Sorting a vector in C++
- vector : : resize() in C++ STL
- Modifiers for Vector in C++ STL
- How to reverse a Vector using STL in C++?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.