.size()

LilyS_24's avatar
Published Nov 15, 2024
Contribute to Docs

In C++, the .size() method is used to determine the number of elements in a map.

Syntax

mapName.size();
  • mapName: The map object for which the size is to be checked.

Example

The following example uses .size() to get the number of elements in myMap:

#include <iostream>
#include <map>
int main() {
std::map<int, std::string> myMap;
myMap[1] = "apple";
myMap[2] = "banana";
myMap[3] = "cherry";
std::cout << "The map contains " << myMap.size() << " elements.";
}

The output of the above code will be:

The map contains 3 elements.

Codebyte Example

The below example demonstrates the usage of the .size() method with two maps, vehicles and fruits:

Code
Output
Loading...

All contributors

Contribute to Docs

Learn C++ on Codecademy