C++ set size
The size function in C++ is employed to determine the total count of elements stored within the set data structure.
Syntax
The size_type member type is an unsigned integral data type.
size_type size() const; // until C++ 11
size_type size() const noexcept; //since C++ 11
Parameter
Return value
It provides the count of items within the set.
Complexity
Constant.
Iterator validity
No changes.
Data Races
The container is accessed.
Simultaneously retrieving the elements of a set is considered secure.
Exception Safety
This function never throws exception.
Example 1
Let's explore a straightforward example to determine the cardinality of the set:
#include <set>
#include <iostream>
using namespace std;
int main()
{
set<char> num {'a', 'b', 'c', 'd'};
cout << "num set contains " << num.size() << " elements.\n";
return 0;
}
Output:
num set contains 4 elements.
In the given scenario, the set named num consists of 4 elements. Consequently, invoking size will yield 4 elements.
Example 2
Let's examine a basic illustration to determine the initial size of a set and the size of the set after adding elements:
#include <iostream>
#include <set>
using namespace std;
int main(void) {
set<int> m;
cout << "Initial size of set = " << m.size() << endl;
m = {1,2,3,4,5,6};
cout << "Size of set after inserting elements = " << m.size() << endl;
return 0;
}
Output:
Initial size of set = 0
Size of set after inserting elements = 6
In the aforementioned scenario, the initial set is devoid of any elements, resulting in the size function yielding 0. Upon the insertion of 6 elements thereafter, the size function will then return 6.
Example 3
Let's see a simple example:
#include <iostream>
#include <set>
using namespace std;
int main ()
{
set<int> myset = {100,200,300,400};
while (myset.size())
{
cout << *myset.begin()<< '\n';
myset.erase(myset.begin());
}
return 0;
}
Output:
100
200
300
400
In the aforementioned example, the size function is utilized within a while loop to display the elements of a set until the set's size is reached.
Example 4
Let's see a simple example:
#include <iostream>
#include <set>
#include <string>
using namespace std;
int main() {
typedef set<int> marksSet;
int number;
marksSet marks;
cout<<"Enter three sets of marks: \n";
for(int i =0; i<3; i++)
{
cin>> number; // Get value
marks.insert(number); // Put them in set
}
cout<<"\nSize of phone set is:"<< marks.size();
cout<<"\nList of telephone numbers: \n";
marksSet::iterator p;
for(p = marks.begin(); p!=marks.end(); p++)
{
cout<<(*p)<<" \n ";
}
return 0;
}
Output:
Enter three sets of marks:
78 90 84
Size of phone set is: 3
List of telephone numbers:
78
84
90
The program initially generates marks set through an interactive process. Subsequently, it showcases the overall size of the marks set and lists out all the elements within the set.