C++ STL 中的 set::value_comp() 函式
本文將討論 C++ STL 中的 set::value_comp(),包括其語法、工作原理和返回值。
什麼是 C++ STL 中的 Set?
C++ STL 中的 Set 是一種容器,它必須包含按特定順序排列的唯一元素。Set 必須包含唯一元素,因為元素的值標識該元素。一旦將值新增到 Set 容器中,就不能修改它,儘管我們仍然可以從 Set 中刪除或新增值。Set 使用二叉搜尋樹。
什麼是 set::value_comp()?
value_comp() 是 C++ STL 中的一個內建函式,宣告在 <set> 標頭檔案中。value_comp() 返回比較物件的副本,該物件由 Set 容器用於比較。預設情況下,此物件小於運算子的物件。它是一種函式指標或函式物件,用於比較同一型別 Set 中的兩個值的比較,如果第一個元素小於容器中的第二個元素,則返回 true,否則返回 false。在 Set 容器中,值本身就是鍵,因此它們以排序的格式放置在 Set 容器中,因此函式 value_comp() 和 key_comp() 的工作方式類似。
語法
comparison_object set_name.value_comp();
引數
此函式不接受任何引數。
返回值
此函式返回關聯 Set 容器的比較物件。
示例
Input: set <int> myset = {9, 8, 7, 6, 5}; set<int>::value_compare cmp = myset.value_comp() Output: 5 6 7 8 9
示例
#include <bits/stdc++.h> using namespace std; int main(){ set<int> Set; set<int>::value_compare cmp = Set.value_comp(); for (int i = 0; i <= 10; i++) Set.insert(i); cout<<"elements in set are: "; int front = *Set.rbegin(); set<int>::iterator i = Set.begin(); do { std::cout << *i << " "; } while (cmp(*(++i), front)); std::cout << '\n'; return 0; }
輸出
如果執行上述程式碼,將生成以下輸出:
elements in set are : 0 1 2 3 4 5 6 7 8 9
廣告