How can we calculate the number of keys in a map in C++?
One option:
You can use the size() function of a map to count the number of keys in the map. The size() function returns the number of key-value pairs in the map, which is the same as the number of keys. Here is an example code:
#include <iostream>
#include <map>
int main() {
std::map<int, std::string> myMap;
myMap[1] = "Apple";
myMap[2] = "Banana";
myMap[3] = "Orange";
int keyCount = myMap.size();
std::cout << "The number of keys in the map is: " << keyCount << std::endl;
return 0;
}
The output result is:
The number of keys in the map is: 3