C++ Unordered_set::size() Function
TheC++std::unordered_set::size() function is used to return the number of elements in the unordered_set container. or we can say that this function calculates the distance between begin() and end(). If the unordered_set does not contain any elements, then this function returns 0.
Syntax
Following is the syntax of std::unordered_set::size.
size_type size() const noexcept;
Parameters
This function does not accepts any parameter.
Return Value
This function returns the number of elements in the unordered_set container.
Example 1
Consider the following example, where we are going to demonstrate the usages of unordered_set::size() function.
#include <iostream>
#include <string>
#include <unordered_set>
int main () {
std::unordered_set<std::string> myset;
std::cout << "0. size: " << myset.size() << std::endl;
myset = {"sairamkrishna","mammahe"};
std::cout << "1. size: " << myset.size() << std::endl;
myset.insert ("kittuprasad");
std::cout << "2. size: " << myset.size() << std::endl;
myset.erase ("tutorialspoint");
std::cout << "3. size: " << myset.size() << std::endl;
return 0;
}
Output
If we run the above code it will generate the following output −
0. size: 0 1. size: 2 2. size: 3 3. size: 3
Example 2
Let's look at the following example, where we are going to use the unordered_set::size() function to get the total size of the set and also displaying all the elements of myUset.
#include <iostream>
#include <string>
#include <unordered_set>
using namespace std;
int main () {
unordered_set<int> myUset = {1, 2, 3, 4, 5};
int size = myUset.size();
cout<<"Total size of unordered set: "<<size<<endl;
cout<<"Each element of the unordered_set: ";
for(auto it: myUset)
cout<<it<<" ";
return 0;
}
Output
Following is the output of the above code −
Total size of unordered set: 5 Each element of the unordered_set: 5 4 3 2 1
Example 3
In the following example, we are going to consider the empty unordered_set and applying the unordered_set::size() function to get the total size of the unordered_set before and after the insertion of elements.
#include <iostream>
#include <string>
#include <unordered_set>
using namespace std;
int main () {
unordered_set<int> myUset;
int size = myUset.size();
cout<<"Total size of unordered set: "<<size<<endl;
myUset.insert({10, 20, 30});
int tSize = myUset.size();
cout<<"Total size of unordered set after insertion: "<<tSize<<endl;
return 0;
}
Output
Output of the above code is as follows −
Total size of unordered set: 0 Total size of unordered set after insertion: 3