.find()
Published Mar 27, 2025
Contribute to Docs
The .find()
method searches for an element with a given key in a std::map
. If the key exists, .find()
returns an iterator pointing to the key-value pair; otherwise, it returns map.end()
.
Syntax
mapName.find(key);
Parameters:
key
: The key to search for in the map.
Return value:
- If the key is found, returns an iterator pointing to the key-value pair.
- If the key is not found, returns an iterator to
map.end()
.
Example
This example demonstrates using std::map
and the .find()
method to check for an animal’s existence and retrieve its lifespan efficiently:
#include <iostream>#include <map>int main() {std::map<std::string, int> lifeSpan = {{"Giraffe", 26},{"Goat", 15},{"Lion", 10},{"Tiger", 8}};auto it = lifeSpan.find("Lion");if (it != lifeSpan.end()) {std::cout << "Lion found! Lifespan: " << it->second << " years.\n";} else {std::cout << "Lion not found in the map.\n";}return 0;}
The code above results in the following output:
Lion found! Lifespan: 10 years.
Codebyte Example
Run the following codebyte example to understand how to use .find()
to search for a key in a map:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C++ on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn C++
Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.Beginner Friendly11 hours