Junior — Middle
What algorithms are used when removing an element from std::vector, and what is the associated time complexity?
sobes.tech AI
Answer from AI
When removing an element from std::vector, an algorithm shifts all subsequent elements one position to the left to fill the gap. This is because std::vector stores elements in a contiguous block of memory.
The time complexity of removing an element depends on its position:
- If the last element is removed, the operation is performed in O(1) time, as the vector size is simply decreased.
- If an element in the middle or beginning is removed, all subsequent elements are shifted, resulting in O(n) in the worst case, where n is the number of elements after the removed one.
Example of removing an element by index:
#include <vector>
#include <iostream>
int main() {
std::vector<int> v = {1, 2, 3, 4, 5};
int index_to_remove = 2; // removing the element with value 3
v.erase(v.begin() + index_to_remove);
for (int x : v) {
std::cout << x << ' ';
}
// Output: 1 2 4 5
}