1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[C++] The time complexity of vector push_back

Last updated at Posted at 2016-10-20

About the Storage of vector

The c++ reference has the explanation about storage of vector. The actual size of vector may greater than the size of elements it includes.

Instead, vector containers may allocate some extra storage to accommodate for possible growth, and thus the container may have an actual capacity greater than the storage strictly needed to contain its elements (i.e., its size).

Time complexity of push_back

Usually the time complexity of push_back is constant. But the push_back method may not always with time complexity of O(1) when reallocation happens.

Constant (amortized time, reallocation may happen).
If a reallocation happens, the reallocation is itself up to linear in the entire size.

Example Code

vector<int> array(10000000, 1);
cout << array.capacity() << endl;
array.push_back(2); // Reallocation happens
cout << array.capacity() << endl;
10000000
20000000

Reference
http://www.cplusplus.com/reference/vector/vector/

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?