Junior
What is the complexity of removing an element from the beginning of a vector in C++?
sobes.tech AI
Answer from AI
O(n), where n is the number of elements in the vector after the removal. Removing an element from the beginning causes all subsequent elements to shift one position to the left to fill the vacated space.
#include <vector>
#include <iostream>
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
// Remove the first element
if (!vec.empty()) {
vec.erase(vec.begin()); // O(n) operation
}
// After removal: {2, 3, 4, 5}
return 0;
}