C++ .count()
Anonymous contributor
Published Nov 8, 2024
Contribute to Docs
The .count() method in C++ for std::map is used to determine the presence of a specific key in the map. Since all keys in a map are unique, the function returns:
- 1 if the key exists in the container.
- 0 if the key does not exist.
Syntax
mapName.count(key)
mapName: Refers to the specific map being accessed.key: Represents the value that will be searched for inmapName.
Example
In the following example, the .count() method is used to check whether the keys "coconuts" and "strawberries" exist in the fruits map:
#include <iostream>#include <map>#include <string>int main() {// Initializing map with itemsstd::map<std::string, int> fruits {{"apples", 50}, {"bananas", 100}, {"coconuts", 20}, {"dates", 500}};// Checking if "coconuts" existsstd::string key = "coconuts";if (fruits.count(key) > 0) {std::cout << "There are " << fruits[key] << " " << key << ".\n"; // If key exists, print the count} else {std::cout << "There are no " << key << ".\n"; // If key does not exist, print a message}// Checking if "strawberries" existskey = "strawberries";if (fruits.count(key) > 0) {std::cout << "There are " << fruits[key] << " " << key << ".\n"; // If key exists, print the count} else {std::cout << "There are no " << key << ".\n"; // If key does not exist, print a message}return 0;}
The above code produces the following output:
There are 20 coconuts.There are no strawberries.
Codebyte Example
The example below illustrates a scenario in which the .count() method is used to check whether an array of elements exists in a map:
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
- 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