當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。