C++ map - size() Function
The C++ map::size function is used to find out the total number of elements in the map.
Note: Map is an ordered data container which implies all its elements are ordered all the time.
Syntax
size_type size() const;
size_type size() const noexcept;
Parameters
No parameter is required.
Return Value
Number of elements present in the map.
Time Complexity
Constant i.e, Θ(1).
Example:
In the example below, the map::size function is used find out the total number of elements in a map called MyMap.
#include <iostream> #include <map> using namespace std; int main (){ map<int, string> MyMap; MyMap[101] = "John"; MyMap[102] = "Marry"; MyMap[103] = "Kim"; MyMap[104] = "Jo"; MyMap[105] = "Ramesh"; cout<<"Map size is: "<<MyMap.size()<<"\n"; cout<<"Three key/element pairs are added in the Map.\n"; MyMap[106] = "Suresh"; MyMap[107] = "Jack"; MyMap[108] = "Adam"; cout<<"Now, Map size is: "<<MyMap.size()<<"\n"; return 0; }
The output of the above code will be:
Map size is: 5 Three key/element pairs are added in the Map. Now, Map size is: 8
❮ C++ <map> Library