Horje
How to Find the Size of a Map in C++?

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 the same key values. In this article, we will learn how to find the size of a map in C++ STL.

Example:

Input: 
myMap = { {1, "Sravan"},
                    {2, "Bobby"},
                    {3, "Srijay"},
                    {4, "Riya"} }
Output:
Size of map: 4

Find the Size of a Map in C++

In C++, you can find the size of a map using the std::map::size() member function of the std::map container. This function returns the number of key-value pairs stored in the map.

C++ Program to Find the Size of a Map

C++

// C++ program to find the size of the map
#include <iostream>
#include <map>
using namespace std;
  
int main()
{
    // Create map - students_data
    map<int, string> students_data;
  
    // Insert 10 values into the above map
    students_data.insert(make_pair(1, "Sravan"));
    students_data.insert(make_pair(2, "Bobby"));
    students_data.insert(make_pair(3, "Siva Nagulu"));
    students_data.insert(make_pair(4, "Bhavanarayana"));
    students_data.insert(make_pair(5, "Ojaswi"));
    students_data.insert(make_pair(6, "Gnanesh"));
    students_data.insert(make_pair(7, "Sireesha"));
    students_data.insert(make_pair(8, "Priyank Chowdhary"));
    students_data.insert(make_pair(9, "Rohith"));
    students_data.insert(make_pair(10, "Ravi Kumar"));
  
    // Display the map size using the map::size() function.
    cout << "Total Students: " << students_data.size();
    cout << endl;
    return 0;
}

Output

Total Students: 10

Time Complexity: O(1)
Space Complexity: O(1)

Time complexity: O(n)
Auxiliary Space: O(n)




Reffered: https://www.geeksforgeeks.org


C++

Related
How to Find the Intersection of Two Vectors in C++? How to Find the Intersection of Two Vectors in C++?
How to Find Union of Two Vectors in C++? How to Find Union of Two Vectors in C++?
How to Create a Vector of Pairs in C++? How to Create a Vector of Pairs in C++?
How to Create a Set of Arrays in C++? How to Create a Set of Arrays in C++?
How to Create a Set of Sets in C++? How to Create a Set of Sets in C++?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
13