這個find_by_order()是一個內置的函數有序集這是一個基於策略的數據結構在C++中。基於策略的數據結構不屬於C++標準模板庫但的g ++編譯器支持它們。
有序集是g ++中基於策略的數據結構,可以按排序的順序維護唯一的元素。它以O(logN)複雜度執行STL中Set所執行的所有操作。除此之外,還以O(logN)複雜度執行以下兩個操作:
- order_of_key (K): Number of items strictly smaller than K.
- find_by_order(k): Kth element in a Set (counting from zero).
find_by_order()函數接受一個稱為K的鍵作為參數,並將迭代器返回給Kth集合中最大的元素。
例子:
Considering a Set S = {1, 5, 6, 17, 88},
s.find_by_order(0):Returns the 0th largest element, i.e. the minimum element, i.e. 1.
s.find_by_order(2):Returns the 2nd largest element, i.e. 6.Note: If K >= N, where N is the size of the set, then the function returns either 0 or in some compilers, the iterator to the smallest element.
下麵是C++中find_by_order()函數的實現:
C++ 14
// C++ program to implement find_by_order()
// for Policy Based Data Structures
#include <bits/stdc++.h>
// Importing header files
#include <ext/pb_ds/assoc_container.hpp>
using namespace std;
using namespace __gnu_pbds;
// Declaring Ordered Set
typedef tree<int, null_type, less<int>, rb_tree_tag,
tree_order_statistics_node_update>
pbds;
// Driver Code
int main()
{
int arr[] = {1, 5, 6, 17, 88};
int n = sizeof(arr)/sizeof(arr[0]);
pbds S;
// Traverse the array
for (int i = 0; i < n; i++) {
// Insert array elements
// into the ordered set
S.insert(arr[i]);
}
// Returns iterator to 0-th
// largest element in the set
cout << *S.find_by_order(0) << " ";
// Returns iterator to 2-nd
// largest element in the set
cout << *S.find_by_order(2);
return 0;
}
輸出:
1 6
注:本文由純淨天空篩選整理自p1173mayank大神的英文原創作品 find_by_order() in C++。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。