C++ Vector erasing elements

In C++, std::vector provides several ways to erase elements. Here are the most common methods:


1. Erase a Single Element

You can remove an element at a specific position using an iterator.

#include <iostream>
#include <vector>
using namespace std;

int main() {
vector<int> v = {1, 2, 3, 4, 5};

// Erase the element at index 2 (value 3)
v.erase(v.begin() + 2);

// Print the vector
for (int x : v) {
cout << x << " ";
}

return 0;
}

Output:

1 2 4 5

2. Erase a Range of Elements

Remove multiple elements by specifying a range of iterators.

#include <iostream>
#include <vector>
using namespace std;

int main() {
vector<int> v = {1, 2, 3, 4, 5};

// Erase elements from index 1 to 3 (values 2, 3, and 4)
v.erase(v.begin() + 1, v.begin() + 4);

// Print the vector
for (int x : v) {
cout << x << " ";
}

return 0;
}

Output:

1 5

3. Erase Elements Conditionally

Use std::remove_if with erase to remove elements based on a condition.

#include <iostream>
#include <vector>
#include <algorithm> // for std::remove_if
using namespace std;

int main() {
vector<int> v = {1, 2, 3, 4, 5, 6};

// Remove all even numbers
v.erase(remove_if(v.begin(), v.end(), [](int x) { return x % 2 == 0; }), v.end());

// Print the vector
for (int x : v) {
cout << x << " ";
}

return 0;
}

Output:

1 3 5

4. Clear the Entire Vector

Remove all elements using clear().

#include <iostream>
#include <vector>
using namespace std;

int main() {
vector<int> v = {1, 2, 3, 4, 5};

// Clear the vector
v.clear();

// Print the size of the vector
cout << "Size after clear: " << v.size() << endl;

return 0;
}

Output:

Size after clear: 0

5. Erase Using a Loop

To remove specific elements in a loop, use iterators carefully to avoid invalidating them.

#include <iostream>
#include <vector>
using namespace std;

int main() {
vector<int> v = {1, 2, 3, 4, 5};

// Remove all elements greater than 3
for (auto it = v.begin(); it != v.end(); ) {
if (*it > 3) {
it = v.erase(it); // Erase and update iterator
} else {
++it; // Increment iterator
}
}

// Print the vector
for (int x : v) {
cout << x << " ";
}

return 0;
}

Output:

1 2 3

Key Notes:

  1. Iterator Invalidation: Be cautious when erasing elements. Erasing modifies the vector, so iterators to subsequent elements may become invalid.
  2. Efficient Erase Patterns: For conditional removal, combining std::remove_if and erase is often more efficient than manually erasing in a loop.
  3. Clear vs Erase: Use clear() when you want to empty the vector entirely, and erase for more selective removal.
Scroll to Top