The data structure you are looking for is a statistics tree, which is a binary search tree in which each node stores the size of the subtree embedded in that node.
This supports all of the above operations in O (log n).
There is a tree of order statistics in the GNU Policy-Based Data Structures (part of GNU C ++).
The code looks something like this:
#include <iostream> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; typedef tree< int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> set_t; int main() { set_t s; s.insert(12); s.insert(50); s.insert(30); s.insert(20); cout << "1st element: " << *s.find_by_order(1) << '\n'; // 20 cout << "Position of 30: " << s.order_of_key(30) << '\n'; // 2 return 0; }
Live demo .
[Derived from this answer ]
source share