In C++, set::size() function is a built-in used to find the number of elements in the given set container. It is the member function of std::set class defined inside <set> header file. In this article, we will learn about the std::set::size() method in C++.
Example:
// C++ Program to illustrate the use of
// set::size() method
#include <bits/stdc++.h>
using namespace std;
int main() {
set<int> s = {1, 5, 7};
cout << s.size();
return 0;
}
Output
3
Syntax of set::size()
s.size();
Parameters
- This function does not require any parameter.
Return Value
- Returns the number of elements in the std::set container.
- If the set is empty, it returns 0.
More Examples of set::size()
The following examples demonstrates the use of set::size() function in different scenarios:
Example 1: Find the Size of Set Container
// C++ Program to find the size of std::set
// using set::size() method
#include <bits/stdc++.h>
using namespace std;
int main() {
set<int> s = {11, 13, 56, 67, 89};
// Find the size using set::size()
cout << s.size() << endl;
// Delete the first element of set container
s.erase(s.begin());
// Again find the size of set
cout << s.size();
return 0;
}
Output
5 4
Example 2: Find the Size of Empty Set
// C++ Program to find the size of empty set
// using set::size()
#include <bits/stdc++.h>
using namespace std;
int main() {
set<int> s;
// Find the size of empty set container
cout << s.size();
return 0;
}
Output
0