Search code examples
c++performancec++11c++17standards

Why does std::set::find not provide a hint iterator?


#include <set>
#include <vector>

using Value = std::vector<int>;

int main()
{
    auto coll = std::set<Value>{};

    // ......
    // Insert many values here.
    // ......

    auto new_value = Value{1, 2, 3};
    auto const pos = coll.find(new_value);

    if (pos != coll.end())
    {
        // Good
        coll.emplace_hint(coll.erase(pos), std::move(new_value));
    }
    else
    {
        // Performance penalty!
        // No hint here, though coll.find(new_value) knows that.
        coll.emplace(std::move(new_value));
    }
}

Why does std::set::find not provide a hint iterator?


Solution

  • The result of std::set::lower_bound() is usable as a hint for emplace_hint(). So just use lower_bound() instead of find(), and check if the key returned by lower_bound() matches what you were looking for, instead of checking if the iterator returned by find() is end().