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


C++ set equal_range()用法及代碼示例

set::equal_range()是C++ STL中的內置函數,它返回對的迭代器。該對是指包含容器中所有具有等於k的鍵的元素的範圍。由於set包含唯一元素,因此下界將是元素本身,上限將指向鍵k之後的下一個元素。如果沒有與鍵K匹配的元素,則根據容器的內部比較對象(key_comp),返回的範圍的長度為0,兩個迭代器均指向大於k的第一個元素。如果鍵超過了set容器中的最大元素,它將返回一個指向set容器中最後一個元素的迭代器。

用法:

set_name.equal_range(key) 

參數:該函數接受一個強製性參數鍵,該鍵指定要返回其在設置容器中的範圍的鍵。


返回值:該函數返回一個成對的迭代器。 (key_comp)。該對是指包含容器中所有具有等於k的鍵的元素的範圍。由於set包含唯一元素,因此下界將是元素本身,上限將指向鍵k之後的下一個元素。如果沒有匹配鍵K的元素,則根據容器的內部比較對象(key_comp),返回的範圍的長度為0,兩個迭代器均指向大於k的第一個元素。如果鍵超過了set容器中的最大元素,它將返回一個指向set容器中最後一個元素的迭代器。

以下示例程序旨在說明上述函數。

// CPP program to demonstrate the 
// set::equal_range() function 
#include <bits/stdc++.h> 
using namespace std; 
int main() 
{ 
  
    set<int> s; 
  
    s.insert(1); 
    s.insert(4); 
    s.insert(2); 
    s.insert(5); 
    s.insert(3); 
  
    // prints the set elements 
    cout << "The set 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(2); 
    cout << "\nThe lower bound of 2 is " << *it.first; 
    cout << "\nThe upper bound of 2 is " << *it.second; 
  
    // Function returns the last element 
    it = s.equal_range(8); 
    cout << "\nThe lower bound of 8 is " << *it.first; 
    cout << "\nThe upper bound of 8 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 set elements are: 1 2 3 4 5 
The lower bound of 2 is 2
The upper bound of 2 is 3
The lower bound of 8 is 5
The upper bound of 8 is 5
The lower bound of 0 is 1
The upper bound of 0 is 1


相關用法


注:本文由純淨天空篩選整理自gopaldave大神的英文原創作品 set equal_range() function in C++ STL。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。