C++ unordered_set of vectors

Sure you can. You’ll have to come up with a hash though, since the default one (std::hash<std::vector<int>>) will not be implemented. For example, based on this answer, we can build:

struct VectorHash {
    size_t operator()(const std::vector<int>& v) const {
        std::hash<int> hasher;
        size_t seed = 0;
        for (int i : v) {
            seed ^= hasher(i) + 0x9e3779b9 + (seed<<6) + (seed>>2);
        }
        return seed;
    }
};

And then:

using MySet = std::unordered_set<std::vector<int>, VectorHash>;

You could also, if you so choose, instead add a specialization to std::hash<T> for this type (note this could be undefined behavior with std::vector<int>, but is definitely okay with a user-defined type):

namespace std {
    template <>
    struct hash<std::vector<int>> {
        size_t operator()(const vector<int>& v) const {
            // same thing
        }
    };
}

using MySet = std::unordered_set<std::vector<int>>;

Leave a Comment