简体   繁体   中英

std::unordered_map - operator != and user defined value

Here is an example code:

struct T
{
    int x;
    int y;

    bool operator !=(const T& t) const 
    {
        return std::tie(x, y) != std::tie(t.x, t.y);
    }
};

int main()
{
    std::unordered_map<int, T> m1;
    std::unordered_map<int, T> m2;

    if (m1 != m2) //compilation error
    {
    
    }
}

I need to use operator!= for the unordered maps. The code doesn't compile because operator== is not found. I can fix it this way:

bool operator ==(const T& t) const 
{
    return std::tie(x, y) == std::tie(t.x, t.y);
}

and then compare maps this way:

if(!(m1 == m2))

Is it an optimal solution or maybe there is a way to use operator!= directly?

The requirements of comparing std::unordered_map is for the key type to be EqualityComparable. This means that T must be able to evaluate the expression a == b where a,b are both of type T .

If all you want to do is compare the equality of these maps, you should define the == operator instead.

If you want to have both the operators, I suggest defining != in terms of == like you have shown, but you can do it the other way around too.

Note that in C++20 you only need to define operator == and the inverse operator != will be defined for you.

See https://en.cppreference.com/w/cpp/container/unordered_map/operator_cmp and https://en.cppreference.com/w/cpp/named_req/EqualityComparable for more details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM