C++ Logo

std-proposals

Advanced search

[std-proposals] Q: invariant for unordered_set and unordered_map "hash" and "comp" argument

From: Александр Поваляев <apovalyaev_at_[hidden]>
Date: Fri, 20 Nov 2026 22:21:01 +0300
Colleagues, good morning!

unordered_set container allos "hash" and "compare" functions specifications
through template arguments. Something like this "unordered_set<string,
hash<string>, HashCmp> a;". On the other hand there is neither invariant
specified (in cppreference or any other relevant web resources) for these
two functions ("hash" and "compare"), nor any runtime or compile time
assert-like functionality to support consistent logic.
Why is this necessary (invariant or check)?
Because in practice we can face out a stupid, but still real-life
scenarios, when all these associative staff would malfunction.
Here is an example:

#include <unordered_set>

#include <string>

#include <iostream>


using namespace std;


struct HashCmp {


   bool operator ()(const string& left, const string& right) const {

       return left.size() == right.size();

   }

};


int main() {


    unordered_set<string, hash<string>, HashCmp> a;

    a.emplace("AAAA");

    a.emplace("BBBB");

    a.emplace("CCCC");


    cout << a.count("AAAA") << " " << a.count("BBBB") << " " <<
a.count("CCCC") << endl;

}


Do you think it will output "1 1 1"?

On my laptop this scenario shows "1 1 0".


Regards,

Alex

Received on 2026-11-20 19:21:15