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


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


set::upper_bound()是C++ STL中的內置函數,該函數返回一個迭代器,該迭代器指向剛好大於k的下一個元素。如果參數中傳遞的 key 超過了容器中的最大 key ,則迭代器將返回指向設置容器中最後一個元素的下一個元素(可以使用set end()函數標識)。

用法:

set_name.upper_bound(key)

參數:此函數接受單個強製性參數鍵,該鍵指定要返回其上限的元素。


返回值:該函數返回一個迭代器,該迭代器指向剛好大於k的下一個元素。如果參數中傳遞的鍵超過了容器中的最大鍵,則迭代器指向std::end(,它指向集合中最後一個元素旁邊的元素。

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

// CPP program to demonstrate the 
// set::upper_bound() function 
#include <bits/stdc++.h> 
using namespace std; 
int main() 
{ 
    set<int> s; 
  
    // Function to insert elements 
    // in the set container 
    s.insert(1); 
    s.insert(4); 
    s.insert(2); 
    s.insert(5); 
    s.insert(6); 
  
    cout << "The set elements are: "; 
    for (auto it = s.begin(); it != s.end(); it++) 
        cout << *it << " "; 
  
    // when 2 is present 
    // points to next element after 2 
    auto it = s.upper_bound(2); 
    cout << "\nThe upper bound of key 2 is "; 
    cout << (*it) << endl; 
  
    // when 3 is not present 
    // points to next greater after 3 
    it = s.upper_bound(3); 
    cout << "The upper bound of key 3 is "; 
    cout << (*it) << endl; 
  
    return 0; 
}
輸出:
The set elements are: 1 2 4 5 6 
The upper bound of key 2 is 4
The upper bound of key 3 is 4

示例2:下麵是一個更好的代碼,它還檢查給定元素是否大於或等於最大元素。

// CPP program to demonstrate the 
// set::upper_bound() function 
#include <bits/stdc++.h> 
using namespace std; 
int main() 
{ 
    set<int> s; 
  
    // Function to insert elements 
    // in the set container 
    s.insert(1); 
    s.insert(4); 
    s.insert(2); 
    s.insert(5); 
    s.insert(6); 
  
    int key = 8; 
    auto it = s.upper_bound(key); 
    if (it == s.end()) 
        cout << "The given key is greater "
                "than or equal to the largest element \n"; 
    else
        cout << "The immediate greater element "
             << "is " << *it << endl; 
  
    key = 3; 
    it = s.upper_bound(key); 
    if (it == s.end()) 
        cout << "The given key is greater "
                "than or equal to the largest element \n"; 
    else
        cout << "The immediate greater element "
             << "is " << *it << endl; 
  
    return 0; 
}
輸出:
The given key is greater than or equal to the largest element 
The immediate greater element is 4


相關用法


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