Open In App

order_of_key() in C++

The order_of_key() is a builtin function of Ordered Set which is a Policy Based Data Structure in C++. Policy-based data structures are not part of the C++ standard library but g++ compiler supports them.

Ordered set is a policy based data structure in g++ that keeps the unique elements in sorted order. It performs all the operations as performed by the set data structure in STL in log(n) complexity and performs two additional operations also in log(n) complexity .



Two important operations that we can perform in these data structures:

  • order_of_key: The number of items in a set that are strictly smaller than k
  • find_by_order: It returns an iterator to the ith largest element

The order_of_key() function accepts a key and returns the number of elements in the ordered set which are strictly less than the key passed to it as a parameter.



For example,

Let us assume we have a set s : {1, 5, 6, 17, 88}, then :
s.order_of_key(6) : Count of elements strictly smaller than 6 is 2.
s.order_of_key(25) : Count of elements strictly smaller than 25 is 4.

Comparison with lower_bound() and distance()

Below program illustrate the implementation of order_of_key():




// CPP program to illustrate order_of_key()
// for policy based data structures
  
#include <iostream> 
using namespace std; 
  
// Important header files  
#include <ext/pb_ds/assoc_container.hpp> // Common file 
#include <ext/pb_ds/tree_policy.hpp> 
#include <functional> // for less 
#include <iostream> 
using namespace __gnu_pbds; 
using namespace std; 
  
// Declaring ordered_set
typedef tree<int, null_type, less<int>, rb_tree_tag, 
            tree_order_statistics_node_update> 
    ordered_set; 
  
  
// Driver code 
int main() 
    ordered_set mySet;
      
    // Inserting elements to ordered_set
    mySet.insert(5); 
    mySet.insert(2); 
    mySet.insert(6); 
    mySet.insert(4); 
  
    // count of elements less than 6 
    cout << "Count of elements less than 6::"
        << mySet.order_of_key(6) << endl; 
  
    // number 7 not in the set but it will show the 
    // index number if it was there in sorted array. 
    cout << "Count of elements less than 7 ::"
        << mySet.order_of_key(7) << endl; 
  
    return 0; 

Output:
Count of elements less than 6::3
Count of elements less than 7 ::4

Article Tags :
C++