Is there a way to erase an element from a std::vector without shifting the following elements?
When erasing an element from a std::vector, all elements after it must be shifted one position to the left.However, erasing the last element is constant‑time because no shifting is needed.Example:
std::vector vec{1, 2, 4, 3};
std::cout << "vec == ";
for (int x : vec) std::cout << x << " ";
std::cout << "\n";
std::cout << "erasing last element " << vec.back() << "\n";
vec.pop_back(); // O(1)
std::cout << "vec without last element == ";
for (int x : vec) std::cout << x << " ";
std::cout << "\n";
Question:
Can this property be used to erase any element of a vector without shifting the following elements?