Removing Pairs
Part of the Logic & Flow section of Coddy's C++ journey — lesson 27 of 56.
Sometimes you need to remove key-value pairs from your map when they're no longer needed. The .erase() method provides a straightforward way to delete elements by specifying the key you want to remove.
To remove an element from a map, simply call .erase() with the key as the argument:
std::map<std::string, int> scores;
scores["Alice"] = 95;
scores["Bob"] = 87;
scores["Carol"] = 92;
scores.erase("Bob"); // Removes Bob's entry completelyAfter calling erase("Bob"), the map will only contain Alice and Carol's scores. If you try to erase a key that doesn't exist in the map, the operation simply does nothing - no error occurs.
When iterating over a map with a range-based for loop, each element is a std::pair containing the key and value. You can access the key with .first and the value with .second:
for (auto pair : scores) {
std::cout << pair.first << ": " << pair.second << std::endl;
}This will print each name and score in alphabetical order, since std::map keeps its keys sorted automatically.
This method is particularly useful for maintaining clean data structures, removing outdated information, or implementing features where users can delete entries from your application.
Challenge
EasyCreate a program that manages a contact directory using a std::map. Your program will store contact names and phone numbers, then allow users to remove specific contacts from the directory using the .erase() method.
The following inputs will be provided:
- An integer
nrepresenting the number of initial contacts - Then
npairs of inputs:- A string representing the contact name
- A string representing the phone number
- An integer
mrepresenting the number of contacts to remove - Then
mstrings representing contact names to remove
Your program should:
- Create a
std::map<std::string, std::string>namedcontacts - Read the number of initial contacts and populate the map with contact names and phone numbers
- Print the initial contact directory in the format shown below
- Read the number of contacts to remove
- For each contact name to remove, use the
.erase()method to remove it from the map - Print the updated contact directory after all removals
Use the following exact output format:
Initial directory:
Initial Contact Directory:
[contact1]: [phone1]
[contact2]: [phone2]
[contact3]: [phone3]
...Updated directory after removals:
Updated Contact Directory:
[remaining_contact1]: [phone1]
[remaining_contact2]: [phone2]
...If the directory becomes empty after all removals, print:
Updated Contact Directory:
Directory is emptyThe contacts should be printed in the order they appear when iterating through the map (alphabetical order by contact name). Use a range-based for loop to iterate through the map both times, accessing each key-value pair with pair.first for the contact name and pair.second for the phone number. Remember that attempting to erase a contact that doesn't exist will not cause an error - the map will simply remain unchanged.
Try it yourself
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
// Read number of initial contacts
int n;
cin >> n;
// Create the contacts map
map<string, string> contacts;
// Read initial contacts
for (int i = 0; i < n; i++) {
string name, phone;
cin >> name >> phone;
// TODO: Add contact to the map
}
// Print initial directory
cout << "Initial Contact Directory:" << endl;
// TODO: Print all contacts using range-based for loop
// Read number of contacts to remove
int m;
cin >> m;
// Remove contacts
for (int i = 0; i < m; i++) {
string nameToRemove;
cin >> nameToRemove;
// TODO: Remove contact using .erase() method
}
// Print updated directory
cout << "Updated Contact Directory:" << endl;
// TODO: Print remaining contacts or "Directory is empty" if empty
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 Practice4Maps (Key-Value Pairs)
Introducing std::mapCreating a MapAccessing and Modifying ValuesChecking for KeysRemoving PairsIterating Over a MapRecap - Word Frequency2Vectors (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