Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iterator++ complexity for stl map [closed]

What's the complexity of iterator++ operation for stl RB-Tree(set or map)? I always thought they would use indices thus the answer should be O(1), but recently I read the vc10 implementation and shockly found that they did not. To find the next element in an ordered RB-Tree, it would take time to search the smallest element in the right subtree, or if the node is a left child and has no right child, the smallest element in the right sibling. This introduce a recursive process and I believe the ++ operator takes O(lgn) time. Am I right? And is this the case for all stl implementations or just visual C++?

Is it really difficult to maintain indices for an RB-Tree? As long as I see, by holding two extra pointers in the node structure we can maintain a doubly linked list as long as the RB-Tree. Why don't they do that?

like image 452
user3351095 Avatar asked Feb 25 '14 12:02

user3351095


1 Answers

The amortized complexity when incrementing the iterator over the whole container is O(1) per increment, which is all that's required by the standard. You're right that a single increment is only O(log n), since the depth of the tree has that complexity class.

It seems likely to me that other RB-tree implementations of map will be similar. As you've said, the worst-case complexity for operator++ could be improved, but the cost isn't trivial.

It quite possible that the total time to iterate the whole container would be improved by the linked list, but it's not certain since bigger node structures tend to result in more cache misses.

like image 116
Steve Jessop Avatar answered Sep 29 '22 17:09

Steve Jessop