Open In App
Related Articles

map::size() in C++ STL

Improve Article
Save Article
Like Article

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.

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



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


Input : map1 = { 
                {1, "India"},
                {2, "Nepal"},
                {3, "Sri Lanka"},
                {4, "Myanmar"}
Output: 4

Input : map2 = {};
Output: 0

// 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;


map1 size: 4
map2 size: 0

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

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 27 Dec, 2018
Like Article
Save Article
Similar Reads