Generate ready-to-paste C++ Order Statistics Tree code. Configure key type, comparator, and duplicate support. One-click copy.
GCC ships an order-statistics tree that most C++ programmers never touch, because using it means remembering two obscure headers, a five-argument template and a namespace nobody types twice. The PBDS Generator writes that boilerplate for you, wrapped in a struct with named methods.
What you get is a red-black tree supporting two operations an ordinary std::set cannot manage in logarithmic time: find_by_order(k) for the k-th smallest element, and order_of_key(x) for the count of elements strictly below x. Those two turn a rank query from an O(n) walk into an O(log n) lookup.
Four key types are offered, from int through pair<int,int> to string, along with an ascending or descending comparator and a tree variable name of your choosing. Code regenerates as you change any of them, entirely in the page.
less and greater, which reverses the meaning of both order operations: with greater, find_by_order(0) returns the largest element.pair<T,int> with an incrementing counter as the tiebreaker.order_of_key queries with {val, INT_MIN} rather than INT_MAX. That distinction is the entire difference between counting elements strictly below val and counting those at or below it.order_of_key and find_by_order instead of erasing a constructed pair, because no stored element ever has the sentinel counter and a direct erase would silently remove nothing.std::set for pure insert and lookup work, roughly 2 to 3 times. Reach for one only when you genuinely need the rank operations.find_by_order with the iterator overload is the usual route.Configure Your PBDS Tree
Generated C++ Code
// PBDS Order Statistics Tree — generated by UtilityToolsLab
// Requires: GCC with policy-based headers
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
// Tree type alias
typedef tree<
int,
null_type,
less<int>,
rb_tree_tag,
tree_order_statistics_node_update
> ordered_set;
// Wrapper with helper methods
struct OST {
ordered_set tree;
void insert(int val) { tree.insert(val); }
// find_by_order: k-th element (0-indexed)
int find_by_order(int k) {
return *tree.find_by_order(k);
}
// order_of_key: number of elements strictly less than val
int order_of_key(int val) { return tree.order_of_key(val); }
void erase(int val) { tree.erase(val); }
int size() { return tree.size(); }
bool empty() { return tree.empty(); }
};
// Usage example:
// OST ost;
// ost.insert(5); ost.insert(3); ost.insert(7);
// cout << ost.order_of_key(5) << endl; // 1 (one element < 5)
// cout << ost.find_by_order(0) << endl; // 3 (smallest)
Key Operations Reference
ost.insert(x)Insert element xost.order_of_key(x)# elements strictly < xost.find_by_order(k)k-th element (0-indexed)ost.erase(x)Remove one occurrence of x