How do I insert and erase elements efficiently with std::vector?

When working with std::vector in C++, inserting and erasing elements efficiently is crucial for performance, especially when dealing with large datasets. Here are some tips and techniques to handle these operations effectively:

Inserting Elements

To insert elements into a std::vector, you can use the push_back() method, which adds an element to the end of the vector. This is an efficient operation, as it usually runs in constant-time (O(1)). However, if the underlying array needs to be resized, it can lead to a potential time complexity of O(n).

If you need to insert an element at a specific position, you can use the insert() method. This operation may take O(n) time because all elements after the insertion point have to be shifted.

Erasing Elements

To remove elements, you can use the erase() method, which also takes O(n) time since it requires shifting elements to fill in the gap left by the erased element. For better performance, consider marking elements as "deleted" rather than actually removing them until you really need to.

Example Code

#include <iostream> #include <vector> using namespace std; int main() { vector vec; // Inserting elements vec.push_back(10); vec.push_back(20); vec.push_back(30); vec.insert(vec.begin() + 1, 15); // Insert 15 at index 1 // Display vector cout << "Vector after insertion: "; for (int x : vec) { cout << x << " "; } cout << endl; // Erasing an element vec.erase(vec.begin() + 1); // Erase element at index 1 // Display vector cout << "Vector after erasing: "; for (int x : vec) { cout << x << " "; } cout << endl; return 0; }

std::vector C++ insertion efficiency erasure efficiency element management