.count()

Anonymous contributor's avatar
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 in mapName.

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 items
std::map<std::string, int> fruits {{"apples", 50}, {"bananas", 100}, {"coconuts", 20}, {"dates", 500}};
// Checking if "coconuts" exists
std::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" exists
key = "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:

Code
Output
Loading...

All contributors

Contribute to Docs

Learn C++ on Codecademy