Removing Elements
Part of the Logic & Flow section of Coddy's C++ journey — lesson 16 of 56.
Sometimes you need to remove elements from a vector when they're no longer needed. Vectors require you to use an iterator with the .erase() method. You can combine std::find() with .erase() to remove elements by value.
Here's how to remove an element from a vector:
std::vector<int> numbers = {10, 20, 30, 40};
auto it = std::find(numbers.begin(), numbers.end(), 20);
if (it != numbers.end()) {
numbers.erase(it); // Removes the element at iterator position
}After calling erase(), the element at that position is removed and all subsequent elements shift down. If you try to find and erase an element that doesn't exist, find() will return end(), and checking for this prevents errors.
This pattern makes element removal safe and predictable. It's particularly useful for maintaining dynamic collections where you need to remove specific items based on user input or program logic. Remember to always check if the iterator is valid before erasing.
Challenge
EasyCreate a program that demonstrates removing elements from a std::vector using the .erase() method combined with std::find(). This challenge will test your understanding of how to safely remove specific elements from a vector and observe the results.
The following inputs will be provided:
- An integer
nrepresenting the number of elements to initially add to the vector - Then
nintegers to be inserted into the vector - An integer
mrepresenting the number of elements to remove - Then
mintegers representing the elements to remove from the vector
Your program should:
- Create an empty
std::vector<int> - Read the number of elements to add and insert them into the vector using
.push_back() - Print the initial vector size after all insertions
- Read the number of elements to remove
- For each element to remove, use
std::find()to locate it, then use.erase()to remove it if found - After each removal attempt, print the current size of the vector
- Finally, iterate through the remaining elements in the vector and print them in order
Use the following exact output format:
Initial vector size:
Initial size: [size]After each removal attempt:
After removing [number]: size = [current_size]Final remaining elements:
Remaining elements: [element1] [element2] [element3] ...Remember that .erase() requires an iterator, so you must use std::find() first to locate the element. Always check if the element was found before erasing. Use a range-based for loop to print the remaining elements in their current order.
Cheat sheet
Use std::find() combined with .erase() to remove a specific element from a vector:
std::vector<int> numbers = {10, 20, 30, 40};
auto it = std::find(numbers.begin(), numbers.end(), 20);
if (it != numbers.end()) {
numbers.erase(it); // Removes element at iterator position
}Always check if the iterator is not equal to end() before erasing to avoid undefined behavior. The .erase() method requires an iterator, not a value directly.
Try it yourself
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
// Read number of elements to add
int n;
cin >> n;
// Create an empty vector
vector<int> myVector;
// Read and insert n elements
for (int i = 0; i < n; i++) {
int element;
cin >> element;
// Insert element into vector
}
// Read number of elements to remove
int m;
cin >> m;
// TODO: Write your code below
// 1. Print initial vector size
// 2. For each element to remove, find it and use .erase() and print size after each removal
// 3. Print remaining elements in the vector
return 0;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Pointers and Memory
What is a Pointer?Address-Of OperatorDereference OperatorNull PointersPointers and ArraysDynamic Memory with 'new'Freeing Memory with 'delete'Recap - Pointer Practice2Vectors (Dynamic Arrays)
Introducing std::vectorCreating a VectorAdding ElementsAccessing ElementsVector SizeIterating with a For LoopRange-Based For LoopRemoving ElementsRecap - Vector Operations5Project: Inventory Tool
Project SetupAdding and Updating Items