My question pertains to the std::map class in the STL of c++. My understanding is that it is implemented using red black trees to allow for O(logn) insertions, deletions, and lookups while maintaining order with respect to the keys.
I encountered a problem recently where I needed to access the ith element in the map, but the class only implements an iterator that can be advanced one entry at a time. In other words I would need to increment the iterator i times to get to the ith element in the map.
Ultimately I'm curious if it's possible to implement std::map such that the lookup of the ith element can be done in O(logn) time rather than O(n) time as it currently stands. I believe this is possible by keeping track of the number of nodes in the left and right subtrees of each node. That would allow for a search for the ith element like this (where node->num_left/right indicate the number of nodes in the left and right subtrees)
Node* getNodeAtIndex(int i) {
Node *cur = root;
int num_to_left=root->num_left, num_to_right=root->num_right;
while (num_to_left != i) {
if (i < num_to_left) { // move left
cur = cur->left;
num_to_left -= (1 + cur->num_right);
num_to_right += (1 + cur->num_right);
} else { // move right
cur = cur->right;
num_to_left += (1 + cur->num_left);
num_to_right -= (1 + cur->num_left);
}
}
return cur;
}
This post: Get index of element in C++ map relates very closely however many answers discuss how the ith element in a map is undefined. However, I believe it is defined in the sense that the "ith" element has i entries in the map with keys less than its key and map.size()-i-1 entries with keys greater than its key.
I'm sure this has been considered, I'm just wondering why it isn't implemented.