multiset equal_range() function in C++ STL

C++Server Side ProgrammingProgramming

In this article we will be discussing the working, syntax and examples of multiset::equal_range() function in C++ STL.

What is a multiset in C++ STL?

Multisets are the containers similar to the set container, meaning they store the values in the form of keys same like a set, in a specific order.

In multiset the values are identified as keys as same as sets. The main difference between multiset and set is that the set has distinct keys, meaning no two keys are the same, in multiset there can be the same keys value.

Multiset keys are used to implement binary search trees.

What is multiset::equal_range()?

multiset::equal_range() function is an inbuilt function in C++ STL, which is defined in <set> header file. equal_range() gets the range of the equal elements in the multiset container.

This function returns the bounds of the range which includes all the elements in the container equal to the parameter we give to the function.

Syntax

ms_name.equal_range(value_type& val);

Parameters

The function accepts one parameter −

  • val − The value whose range we are searching in the container.

Return value

This function returns a pair of lower bound and upper bound of which the values are equal to

Example

Input

std::multiset<int> mymultiset = {1, 2, 2, 3, 4};
mymultiset.equal_range(2);

Output

2 2

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int main(){
   multiset<int> check;
   check.insert(10);
   check.insert(20);
   check.insert(30);
   check.insert(40);
   check.insert(50);
   check.insert(60);
   check.insert(70);
   check.insert(80);
   cout<<"Elements are: ";
   for (auto i = check.begin(); i!= check.end(); i++)
      cout << *i << " ";
   //lower bound and upper bound
   auto i = check.equal_range(30);
   cout<<"\nThe lower bound of 30 is " << *i.first;
   cout<<"\nThe upper bound of 30 is " << *i.second;
   // last element
   i = check.equal_range(20);
   cout<<"\nThe lower bound of 20 is " << *i.first;
   cout<<"\nThe upper bound of 20 is " << *i.second;
   i = check.equal_range(80);
   cout<<"\nThe lower bound of 80 is " << *i.first;
   cout<<"\nThe upper bound of 80 is " << *i.second;
   return 0;
}

Output

Elements are: 10 20 30 40 50 60 70 80
The lower bound of 30 is 30
The upper bound of 30 is 40
The lower bound of 20 is 20
The upper bound of 20 is 30
The lower bound of 80 is 80
The upper bound of 80 is 8
raja
Published on 17-Apr-2020 08:59:32
Advertisements