.count()

Anonymous contributor's avatar
Anonymous contributor
Published Nov 8, 2024
Contribute to Docs

The .count() method checks if a key exists in an unordered map. It returns 1 if the key exists and 0 if it does not.

Syntax

mapName.count(key);
  • mapName: The name of the unordered map.
  • key: The key to check for existence in the map.

Example

The following example demonstrates the use of the .count() method with an unordered map to check for mammals and display their lifespans:

#include <iostream>
#include <unordered_map>
int main() {
// Initializing unordered_map
std::unordered_map<std::string, int> lifeSpan = {
{"Giraffe", 26},
{"Goat", 15},
{"Lion", 10},
{"Tiger", 8}
};
// Checking the existence of elements using .count()
std::string mammals[] = {"Giraffe", "Elephant", "Lion", "Zebra"};
for (const auto& mammal : mammals) {
if (lifeSpan.count(mammal) > 0) {
std::cout << mammal << " exists in the map with an average lifespan of " << lifeSpan[mammal] << " years.\n";
} else {
std::cout << mammal << " does not exist in the map.\n";
}
}
return 0;
}

This example results in the following output:

Giraffe exists in the map with an average lifespan of 26 years.
Elephant does not exist in the map.
Lion exists in the map with an average lifespan of 10 years.
Zebra does not exist in the map.

Codebyte Example

The following codebyte example demonstrates the use of the .count() method with an unordered map to check for the presence of various fruits and their prices:

Code
Output
Loading...

All contributors

Contribute to Docs

Learn C++ on Codecademy