map::size() in C++ STL


Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have same key values.

map::size()
In C++, size() function is used to return the total number of elements present in the map.

Syntax:



map_name.size()

Return Value: It returns the number of elements present in the map.

Examples:

Input : map1 = { 
                {1, "India"},
                {2, "Nepal"},
                {3, "Sri Lanka"},
                {4, "Myanmar"}
               }
        map1.size();
Output: 4

Input : map2 = {};
        map2.size();
Output: 0

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to illustrate
// implementation of size() function
#include <bits/stdc++.h>
using namespace std;
  
int main()
{
    // Take any two maps
    map<int, string> map1, map2;
      
    // Inserting values
    map1.insert(make_pair(1, "India"));
    map1.insert(make_pair(2, "Nepal"));
    map1.insert(make_pair(3, "Sri Lanka"));
    map1.insert(make_pair(4, "Myanmar"));
      
    // Printing the size
    cout << "map1 size: " << map1.size();
    cout << endl;
    cout << "map2 size: " << map2.size();
    return 0;
}

chevron_right


Output:

map1 size: 4
map2 size: 0

Time complexity: Constant i.e. O(1)



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : vaibhavch9876



Article Tags :
Practice Tags :


2


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.