Checking for Elements
Part of the Logic & Flow section of Coddy's C++ journey — lesson 37 of 56.
When working with sets, you often need to check whether a specific element exists before performing operations on it. The .count() method provides a simple way to verify if an element is present in your set.
Just like with maps, the .count() method returns 1 if the element exists in the set, and 0 if it doesn't. This makes it perfect for conditional checks:
std::set<int> numbers = {10, 20, 30};
if (numbers.count(20)) {
std::cout << "Found 20 in the set!" << std::endl;
} else {
std::cout << "20 is not in the set" << std::endl;
}This approach is much safer than trying to access elements directly, especially when you're not sure if they exist. You can use .count() to validate user input, prevent errors, or make decisions based on what's currently stored in your set.
Challenge
EasyCreate a program that demonstrates how to safely check for the existence of elements in a std::set before performing operations on them. This challenge will test your understanding of the .count() method for element verification.
The following inputs will be provided:
- An integer
nrepresenting the number of elements to initially add to the set - Then
nintegers to be inserted into the set - An integer
mrepresenting the number of elements to search for - Then
mintegers to check for existence in the set
Your program should:
- Create an empty
std::set<int> - Read the number of elements to add and insert them into the set using
.insert() - Read the number of elements to search for
- For each search element, use the
.count()method to check if it exists in the set - Print appropriate messages based on whether each element is found or not
- After all searches, print the total number of elements that were found
Use the following exact output format:
For each search result:
Searching for [number]: FoundFor elements not found:
Searching for [number]: Not foundSummary at the end:
Total found: [count] out of [total_searches]Use numbers.count(searchValue) to check if an element exists in the set. If it returns 1, the element exists; if it returns 0, the element doesn't exist. Keep a counter to track how many elements were successfully found during the search operations.
Cheat sheet
Use .count() to check if an element exists in a set. It returns 1 if the element exists, 0 if it doesn't:
std::set<int> numbers = {10, 20, 30};
if (numbers.count(20)) {
std::cout << "Found 20 in the set!" << std::endl;
} else {
std::cout << "20 is not in the set" << std::endl;
}This method is safer than trying to access elements directly and is perfect for conditional checks and input validation.
Try it yourself
#include <iostream>
#include <set>
using namespace std;
int main() {
// Read the number of elements to add to the set
int n;
cin >> n;
// Create an empty set
set<int> numbers;
// Read and insert n elements into the set
for (int i = 0; i < n; i++) {
int element;
cin >> element;
numbers.insert(element);
}
// Read the number of elements to search for
int m;
cin >> m;
int foundCount = 0;
// TODO: Write your code below
// For each search element:
// 1. Read the search value
// 2. Use numbers.count(searchValue) to check if it exists
// 3. Print the appropriate message
// 4. Update foundCount if element is found
// Print the summary
cout << "Total found: " << foundCount << " out of " << m << endl;
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 Items6Sets (Unique Elements)
Introducing std::setCreate Set & Add ElementsChecking for ElementsRemoving ElementsIterating Over a SetRecap - Unique Numbers