📜  C++ STL中的多集equal_range()函数

📅  最后修改于: 2021-05-30 10:17:01             🧑  作者: Mango

multiset :: equal_range()是C++ STL中的内置函数,它返回对的迭代器。该对是指包含容器中所有具有等于k的键的元素的范围。下界将是元素本身,上限将指向键k之后的下一个元素。如果没有与键K匹配的元素,则根据容器的内部比较对象(key_comp),返回的范围的长度为0,两个迭代器均指向大于k的第一个元素。如果键超过set容器中的最大元素,它将返回一个迭代器,该迭代器指向过去在multiset容器中的最后一个元素。

句法:

multiset_name.equal_range(key) 

参数:该函数接受一个强制性参数,该键指定要返回其在多集容器中的范围的键。

返回值:该函数返回一对迭代器。

下面的程序说明了上述函数。

程序1:

// CPP program to demonstrate the
// multiset::equal_range() function
#include 
using namespace std;
int main()
{
  
    multiset s;
  
    // Inserts elements
    s.insert(1);
    s.insert(6);
    s.insert(2);
    s.insert(5);
    s.insert(3);
    s.insert(3);
    s.insert(5);
    s.insert(3);
  
    // prints the multiset elements
    cout << "The multiset elements are: ";
    for (auto it = s.begin(); it != s.end(); it++)
        cout << *it << " ";
  
    // Function returns lower bound and upper bound
    auto it = s.equal_range(3);
    cout << "\nThe lower bound of 3 is " << *it.first;
    cout << "\nThe upper bound of 3 is " << *it.second;
  
    // Function returns the last element
    it = s.equal_range(10);
    cout << "\nThe lower bound of 10 is " << *it.first;
    cout << "\nThe upper bound of 10 is " << *it.second;
  
    // Function returns the range where the
    // element greater than 0 lies
    it = s.equal_range(0);
    cout << "\nThe lower bound of 0 is " << *it.first;
    cout << "\nThe upper bound of 0 is " << *it.second;
  
    return 0;
}
输出:
The multiset elements are: 1 2 3 3 3 5 5 6 
The lower bound of 3 is 3
The upper bound of 3 is 5
The lower bound of 10 is 8
The upper bound of 10 is 8
The lower bound of 0 is 1
The upper bound of 0 is 1

程式2:

// CPP program to demonstrate the
// multiset::equal_range() function
#include 
using namespace std;
int main()
{
  
    multiset s;
  
    // Inserts elements
    s.insert(1);
    s.insert(6);
    s.insert(2);
    s.insert(5);
    s.insert(3);
    s.insert(3);
    s.insert(5);
    s.insert(3);
  
    // prints the multiset elements
    cout << "The multiset elements are: ";
    for (auto it = s.begin(); it != s.end(); it++)
        cout << *it << " ";
  
    // Function returns lower bound and upper bound
    auto it = s.equal_range(3);
    cout << "\nThe lower bound of 3 is " << *it.first;
    cout << "\nThe upper bound of 3 is " << *it.second;
  
    s.erase(it.first, it.second);
  
    // prints the multiset elements after erasing the
    // range
    cout << "\nThe multiset elements are: ";
    for (auto it = s.begin(); it != s.end(); it++)
        cout << *it << " ";
  
    return 0;
}
输出:
The multiset elements are: 1 2 3 3 3 5 5 6 
The lower bound of 3 is 3
The upper bound of 3 is 5
The multiset elements are: 1 2 5 5 6
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”