当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


C++ multiset equal_range()用法及代码示例


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

用法:

multiset_name.equal_range(key) 

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


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

以下示例程序旨在说明上述函数。

示例1:

// CPP program to demonstrate the 
// multiset::equal_range() function 
#include <bits/stdc++.h> 
using namespace std; 
int main() 
{ 
  
    multiset<int> 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 <bits/stdc++.h> 
using namespace std; 
int main() 
{ 
  
    multiset<int> 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


相关用法


注:本文由纯净天空筛选整理自gopaldave大神的英文原创作品 multiset equal_range() function in C++ STL。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。