Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ STL set implementation

Why is the C++ set implemented as a binary tree instead of as a hashset, which can provide average case complexity of O(1) as compared to the O(log n) provided by a binary tree?

like image 869
Cricketer Avatar asked Nov 28 '22 17:11

Cricketer


2 Answers

Because C++ sets are ordered by the T's comparison operator, which makes it possible to iterate over the members in a predictable way. If you know that all you will do with the set is insert, test membership, and/or remove elements, then std::unordered_set, which implements a hashset, exists for that since C++11.

like image 93
Matt Phillips Avatar answered Dec 13 '22 12:12

Matt Phillips


According to John Nagle, from a 2006 posting to comp.lang.c++.moderated:

The actual reason is that the person who was writing the hash table part of the spec didn't finish it in time. That's all.

Standardization processes are like that.

like image 20
rici Avatar answered Dec 13 '22 12:12

rici