.find()

DanielCrigan's avatar
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:

Code
Output
Loading...

All contributors

Contribute to Docs

Learn C++ on Codecademy