Home
Aptitude
Categories


Home » C++ STL

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

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

Return Value:

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

Parameters:

There is no parameter to be passed.

Example:

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

Here, MyMap.size() returns 5.




Program:

#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

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.