C++ .size()
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:
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