C++ Unordered_multimap::size() Function



The C++ std::unordered_multimap::size() function is used to return the number of elements present in the unordered_multimap. If the unordered_multimap does not contain any element then size() function returns 0.

Syntax

Following is the syntax of std::unordered_multimap::size() function.

size_type size() const noexcept;

Parameters

This function does not accepts any parameter.

Return value

This function returns the actual number of element preset in the unordered_multimap's container.

Example 1

In the following example, let's see the usage of the unordered_multimap::size() function.

#include <iostream>
#include <unordered_map>
using namespace std;
int main(void) {
   unordered_multimap<char, int> umm;
   cout << "Initial size of unordered multimap = " << umm.size() << endl;
   umm = {
      {'a', 1},
      {'b', 2},
      {'c', 3},
      {'d', 4},
      {'c', 3},
      {'d', 4}
   };
   cout << "Size of unordered multimap after inserting elements = " << umm.size() << endl;
   return 0;
}

Output

If we run the above code it will generate the following output −

Initial size of unordered multimap = 0
Size of unordered multimap after inserting elements = 6

Example 2

Consider the following example, where we are going to use the size() function to get how many elements are present in the current multimap.

#include <unordered_map>
#include <iostream>
using namespace std;
int main() { 
   unordered_multimap<int,int> numms {{1, 10}, {3, 30}, {5, 50}, {3, 300}, {5, 500}, {7, 70}};
   cout << "numms contains " << numms.size() << " elements.\n";
}

Output

Following is the output of the above code −

numms contains 6 elements.

Example 3

Let's look at the following example, where we are going to find the even keys with their associated values, then store them in another container and later calculate the total number of elements using the multimap.

#include <unordered_map>
#include <iostream>
using namespace std;
int main() { 
   unordered_multimap <int,int> umm {{1, 5}, {2, 30}, {3, 50}, {2, 300}, {4, 70}, {4, 400}, {5, 10}, {6, 20}};
   unordered_multimap <int,int> numms;
   for(auto & it:umm){
      if(it.first % 2 == 0){
         numms.insert({it.first, it.second});
      }
   }
   cout<<"total even key in numms unordered_multimap: "<<numms.size()<<endl;
   return 0;
}

Output

Output of the above code is as follows −

total even key in numms unordered_multimap: 5
Advertisements