Set max_size() function in C++ STL


In this article we are going to discuss the set::max_size() in C++ STL, their syntax, working and their return values.

What is Set in C++ STL?

Sets in C++ STL are the containers which must have unique elements in a general order. Sets must have unique elements because the value of the element identifies the element. Once added a value in set container later can’t be modified, although we can still remove or add the values to the set. Sets are used as binary search trees.

What is set::max_size()?

max_size() is an inbuilt function in C++ STL which is declared in <set> header file. max_size() returns the maximum size of the set container associated with it. In other words, it returns the maximum size that a container can reach, however there is no guarantee it can allocate the elements of that size, it can still fail to allocate the storage to a specific point of a set container.

Syntax

name_of_set.max_size();

Parameter

This function accepts no parameter.

Return value

This function returns the maximum size of the associated set container.

Example

Input: set<int> myset;
myset.max_size();
Output: size of a set before inserting elements: 461168601842738790

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int main(){
   set<int> data_1, data_2;
   data_1.insert(100);
   cout<<"size of a set after inserting values : "<<data_1.max_size()<< endl;
   cout<<"size of a set before inserting values : "<<data_2.max_size();
   return 0;
}

Output

If we run the above code it will generate the following output −

size of a set after inserting values : 461168601842738790
size of a set before inserting values : 461168601842738790

Example

 Live Demo

#include <iostream>
#include <set>
int main (){
   int i;
   std::set<int> Set;
   if(Set.max_size()>1000){
      for (i=0; i<=1000; i++)
         Set.insert(i);
      std::cout<<"There are 1000 elements in a set.\n";
   }
   else
      std::cout<<"There can't be 1000 elements in a set.\n";
   return 0;
}

Output

If we run the above code it will generate the following output −

There are 1000 elements in a set.

Updated on: 05-Mar-2020

760 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements