jeudi 22 août 2019

unordered_set of pairs with unique first elements

I need std::unordered_set of pairs, whose first elements should be different.

Is it correct to hash only first element of pairs, as below?

using Pair = std::pair<int, int>;

struct Eq
{
    bool operator() ( Pair const& lhs,
                      Pair const& rhs ) const
    {
        return (lhs.first == rhs.first);
    }
};

struct Hash
{
    std::size_t operator() ( Pair const &p ) const
    {
        return std::hash<int>()( p.first );
    }
};

// No two pairs with same '.first'.
std::unordered_set<Pair, Hash, Eq> pairs;

for ( Pair const& p : ... )
{
    pairs.insert(p);
}

Aucun commentaire:

Enregistrer un commentaire