Facebook Page Twitter Page LinkedIn Page
× C++ Standard Library C++ STL Library


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 below example, 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\n";

  cout<<"Three elements in the Set is added.\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 in the Set is added.
Now, Set size is: 8

❮ C++ - Set