Set insert doing a weird number of comparisons

I am unable to explain the number of comparisons that std::set does while inserting a new element. Here is an example:

For this code

struct A {
    int i = 0;
    bool operator()(int a, int b)
        return a < b;

int main()
    A a;

    set<int, A> s1(a);

    cout << s1.key_comp().i << endl;

    cout << s1.key_comp().i << endl;

The output is


Why does inserting a second element require 3 comparisons? o_O


This is a side effect of using a red-black tree to implement std::set, which requires more comparisons initially compared to a standard binary tree.

I don't know the particular as they will depend on your std::set implementation, however determining the equality of two items requires two comparisons, as it is based on the fact that not (x < y) and not (y < x) implies x == y.

Depending on how the tree is optimized, you might thus be paying a first comparison to determine whether it should go left or right, and then two comparisons to check whether it's equal or not.

The Standard has no requirement except that the number of comparisons be O(log N) where N is the number of items already in the set. Constant factors are a quality of implementation issue.

Need Your Help

Angular 2 - Http-Testing - Error: "Cannot read property 'getCookie' of null"

javascript http testing angular

Always get this error in console, when running Jasmine Tests with karma on the following code: