C++ STL Tutorial

C++ STL Algorithm

C++ STL Arrays

C++ STL String

C++ STL List

C++ STL Stack

C++ STL Set

C++ STL Queue

C++ STL Vector

C++ STL Map

C++ STL Multimap


map::size() function in C++ STL with Example

C++ STL map::size() function with Example: Here, we are going to learn about the map::size() function in C++ STL with an Example.
Submitted by Vivek Kothari, on November 20, 2018

C++ STL - map::size() function

Maps are a part of the C++ STL and key values in maps are generally used to identify the elements i.e. there is a value associated with every key. map::size() is built-in function in C++ used to find the size of the map. The time complexity of this function is constant i.e. O(1).




There is no parameter to be passed.

Return value

It returns the size of the map i.e. number of elements map container have.

Sample Input and Output

MyMap ={ 
    {1, "c++"},
    {2, "java"},
    {3, "Python"},
    {4, "HTML"},

Here, MyMap.size() returns 5.


#include <bits/stdc++.h> 
using namespace std; 

int main() 
	map<int, string> MyMap1, MyMap2; 

	MyMap1.insert(pair <int, string> (1, "c++")); 
	MyMap1.insert(pair <int, string> (2, "java")); 
	MyMap1.insert(pair <int, string> (3, "Python")); 
	MyMap1.insert(pair <int, string> (4, "HTML")); 
	MyMap1.insert(pair <int, string> (5, "PHP")); 	        

	map <int, string> :: iterator it;
	cout<<"Elements in MyMap1 : "<<endl;
	for (it = MyMap1.begin(); it != MyMap1.end(); it++) 
		cout  <<"key = "<< it->first <<" value = "<< it->second <<endl; 
	cout << "size of MyMap1 : " << MyMap1.size()<<endl;
	cout << "size of MyMap2 : " << MyMap2.size(); 

	return 0; 


Elements in MyMap1 : 
key = 1 value = c++
key = 2 value = java 
key = 3 value = Python 
key = 4 value = HTML 
key = 5 value = PHP
size of MyMap1 : 5 
size of MyMap2 : 0 

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.