find_by_order()是Ordered Set的内置函数,它是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作为参数,并将迭代器返回到 Set 中的第K个最大元素。
例子:
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
// Importing header files
#include
using namespace std;
using namespace __gnu_pbds;
// Declaring Ordered Set
typedef tree, 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
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live