.count()
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_mapstd::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:
All contributors
- Anonymous contributor
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