在本文中,我们将讨论C ++ STL中的set::equal_range()函数,其语法,工作原理和返回值。
C ++ STL中的集合是必须按常规顺序具有唯一元素的容器。集必须具有唯一元素,因为元素的值标识该元素。一旦将值添加到集合容器中,以后就无法修改,尽管我们仍然可以将值删除或添加到集合中。集用作二进制搜索树。
equal_range()函数是C ++ STL中的内置函数,在头文件中定义。此函数返回set容器的范围,该容器包含作为函数的参数传递的值。该集合包含所有唯一值,因此找到范围内的等效值将是单个。如果容器中不存在该值,则范围将为零,两个迭代器均指向第一个位置。
Set1.equal_range(const type_t& value);
该函数接受一个参数,即要查找的元素。
这个函数返回一对,或者我们可以说迭代器的范围从容器的下限开始,直到要在容器中找到的元素为止。
Input: set<int> myset = {10, 20, 30, 40}; Output: lower bound of 30 is 30
#include <bits/stdc++.h> using namespace std; int main(){ set<int> mySet; mySet.insert(10); mySet.insert(20); mySet.insert(30); mySet.insert(40); mySet.insert(50); cout<<"Elements before applying range() Function : "; for (auto i = mySet.begin(); i != mySet.end(); i++) cout << *i << " "; auto i = mySet.equal_range(30); cout<<"\nlower bound of 30 is "<< *i.first; cout<<"\nupper bound of 30 is "<< *i.second; i = mySet.equal_range(40); cout<<"\nlower bound of 40 is " << *i.first; cout<<"\nupper bound of 40 is " << *i.second; i = mySet.equal_range(10); cout<<"\nlower bound of 10 is " << *i.first; cout<<"\nupper bound of 10 is " << *i.second; return 0; }
输出结果
如果我们运行上面的代码,那么它将生成以下输出-
Elements before applying range() Function : 10 20 30 40 50 lower bound of 30 is 30 upper bound of 30 is 40 lower bound of 40 is 40 upper bound of 40 is 50 lower bound of 10 is 10 upper bound of 10 is 20