C++ .find()
Anonymous contributor
Published Feb 11, 2026
The .find() method in C++ searches an std::unordered_set for an element with a specific key. If the key is found, it returns an iterator pointing to that element. If the key is not found, it returns an iterator equal to unordered_set::end(), which represents the past-the-end position in the container.
Syntax
set_name.find(key);
Parameters:
key: The value to search for in theunordered_set.
Return value:
Returns an iterator to the element with a key equivalent to key, if such an element exists. Otherwise, it returns an iterator equal to end().
Example: Using .find() to Locate Existing and Missing Keys
In this example, .find() checks whether specific fruit names exist in the set:
#include <iostream>#include <unordered_set>#include <string>int main() {std::unordered_set<std::string> fruits = {"apple", "banana", "cherry"};// Search for "banana"auto search = fruits.find("banana");if (search != fruits.end()) {std::cout << "Found: " << *search << "\n";} else {std::cout << "Not found\n";}// Search for "grape"if (fruits.find("grape") == fruits.end()) {std::cout << "grape not found in the set.\n";}return 0;}
The output of this code is:
Found: bananagrape not found in the set.
Codebyte Example: Using .find() to Validate Presence of Colors
In this example, .find() tests for a valid color and then checks a color that does not exist:
All contributors
- Anonymous contributor
Learn C++ on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.
- Beginner Friendly.11 hours