# find_by_order() in C++

The **find_by_order()** is a built-in function of __Ordered Set__ which is a __Policy Based Data Structure__ in C++. Policy-based data structures are not part of the C++ Standard Template Library but the g++ compiler supports them.

Ordered Set is a __policy-based data structure in g++__ that maintains **unique** elements in sorted order. It performs all the operations as performed by Set in STL in * O(logN)* complexity.

In addition to that, the following two operations are also performed in

*complexity:*

**O(logN)**

order_of_key(K):Number of items strictly smaller thanK.find_by_order(k):K^{th}element in a Set (counting from zero).

The **find_by_order()** function accepts a key, say **K**, as an argument and returns the iterator to the K^{th} largest element in the Set.

**Examples:**

Considering a Set S = {1, 5, 6, 17, 88},s.find_by_order(0): Returns the 0^{th}largest element, i.e. the minimum element, i.e. 1.s.find_by_order(2): Returns the 2^{nd}largest element, i.e. 6.

Note:IfK >= N, whereNis the size of the set, then the function returns either0or in some compilers, the iterator to the smallest element.

Below is the implementation of **find_by_order()** function in C++:

## 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; ` `}` |

**Output:**

1 6

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the **DSA Self Paced Course** at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer **Complete Interview Preparation Course****.**

In case you wish to attend **live classes **with experts, please refer **DSA Live Classes for Working Professionals **and **Competitive Programming Live for Students**.