C++ Standard Library C++ STL Library

C++ set - size() Function



The C++ set::size function is used to find out the total number of elements in the set.

Note: Set is an ordered data container which implies all its elements are ordered all the time.

Syntax

size_type size() const;
size_type size() const noexcept;

Parameters

No parameter is required.

Return Value

Number of elements present in the set.

Time Complexity

Constant i.e, Θ(1).

Example:

In the example below, the set::size function is used find out the total number of elements in a set called MySet.

#include <iostream>
#include <set>
using namespace std;
 
int main (){
  set<int> MySet{55, 25, 128, 5, 72};

  cout<<"Set size is: "<<MySet.size()<<"\n";

  cout<<"Three elements are added in the set.\n";
  MySet.insert(9);
  MySet.insert(22);
  MySet.insert(54);

  cout<<"Now, Set size is: "<<MySet.size()<<"\n";
  return 0;
}

The output of the above code will be:

Set size is: 5
Three elements are added in the set.
Now, Set size is: 8

❮ C++ <set> Library