Checking for Keys
Part of the Logic & Flow section of Coddy's C++ journey — lesson 26 of 56.
While the square bracket operator is convenient for accessing map values, there's a potential problem: what happens if you try to access a key that doesn't exist? As you learned in the previous lesson, using [] with a non-existent key automatically creates that key with a default value.
Sometimes you want to check if a key exists before accessing it, without accidentally creating new entries. This is where the .count() method becomes useful. It tells you whether a specific key is present in the map.
The .count() method returns 1 if the key exists and 0 if it doesn't:
std::map<std::string, int> scores;
scores["Alice"] = 95;
if (scores.count("Alice")) {
std::cout << "Alice's score: " << scores["Alice"] << std::endl;
} else {
std::cout << "Alice not found" << std::endl;
}This approach lets you safely check for a key's existence and handle both cases appropriately, preventing unwanted entries from being created in your map.
Challenge
EasyCreate a program that manages a library book checkout system using a std::map. Your program will track which books are available and use the .count() method to safely check if books exist before attempting to access their information.
The following inputs will be provided:
- An integer
nrepresenting the number of books in the library - Then
npairs of inputs:- A string representing the book title
- An integer representing the number of copies available
- An integer
mrepresenting the number of book requests to check - Then
mstrings representing book titles to search for
Your program should:
- Create a
std::map<std::string, int>namedlibrary - Read the number of books and populate the map with book titles and their available copies
- Read the number of book requests
- For each book request, use the
.count()method to check if the book exists in the library - Print the appropriate message based on whether the book is found or not
Use the following exact output format:
For each book request:
- If the book exists:
Book "[book title]" is available with [number] copies - If the book doesn't exist:
Book "[book title]" is not available in the library
Use the .count() method in an if-statement to check for the book's existence before accessing its value. If library.count(bookTitle) returns 1, the book exists and you can safely access library[bookTitle] to get the number of copies. If it returns 0, the book doesn't exist in the library.
Cheat sheet
The .count() method checks if a key exists in a map without creating new entries. It returns 1 if the key exists and 0 if it doesn't:
std::map<std::string, int> scores;
scores["Alice"] = 95;
if (scores.count("Alice")) {
std::cout << "Alice's score: " << scores["Alice"] << std::endl;
} else {
std::cout << "Alice not found" << std::endl;
}This prevents accidentally creating unwanted entries when checking for key existence, unlike using the square bracket operator [] which automatically creates keys with default values.
Try it yourself
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
// Read number of books
int n;
cin >> n;
// Create the library map
map<string, int> library;
// Read book information and populate the map
for (int i = 0; i < n; i++) {
string title;
int copies;
cin >> title >> copies;
library[title] = copies;
}
// Read number of book requests
int m;
cin >> m;
// TODO: Write your code below
// Process each book request using .count() method
// Check if book exists and print appropriate message
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