×

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

C++ STL MISC.

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).

Syntax

MapName.size()

Parameter(s)

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"},
    {5,"PHP"}
};

Here, MyMap.size() returns 5.


Example

#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<<endl;
	
	cout << "size of MyMap1 : " << MyMap1.size()<<endl;
	cout << "size of MyMap2 : " << MyMap2.size(); 

	return 0; 
} 

Output

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.