Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to create unordered_set with lambda function

Tags:

c++

c++11

c++14

I get the error

error: call to implicitly-deleted default constructor of '__compressed_pair_elem<(lambda at 
main.cpp:181:16), 1>': _Base1(std::forward<_Tp>(__t)), _Base2() {}

with the following code. What's the mistake I am making and I couldn't understand the error as well.

using namespace std;

auto my_hash = [](vector<int> const& vec){
    size_t seed = vec.size();
    for(auto& i : vec) {
        seed ^= i + 0x9e3779b9 + (seed << 6) + (seed >> 2);
    }
    return seed;
};

using MySet = unordered_set<vector<int>, decltype(my_hash)>;

int main() {
    vector<int> a{1,2,3};
    MySet s;
    return 0;
}
like image 506
user3285099 Avatar asked Oct 29 '18 12:10

user3285099


1 Answers

Closure types are not default-constructible prior to C++20 (see P0624). You need to pass in an instance of your hasher:

constexpr std::size_t bucket_count = 512;
MySet s{bucket_count, my_hash};

live example on wandbox.org


Alternatively, you can use a good old struct:

struct Hasher {
auto operator()(vector<int> const& vec) const {
    size_t seed = vec.size();
    for(auto& i : vec) {
        seed ^= i + 0x9e3779b9 + (seed << 6) + (seed >> 2);
    }
    return seed;
}
};

using MySet = unordered_set<vector<int>, Hasher>;

int main() {
    MySet s;
}

live example on wandbox.org

like image 155
Vittorio Romeo Avatar answered Nov 14 '22 19:11

Vittorio Romeo