Does QMap support custom comparator functions?
Asked Answered
S

3

10

I couldn't find a way to set a custom comparator function for QMap, like I can for std::map (the typename _Compare = std::less<_Key> part of its template arguments).

Does QMap have a way to set one?

Subsequent answered 4/7, 2013 at 7:7 Comment(0)
S
15

It's not documented (and it's a mistake, I think), but in you can specialize the qMapLessThanKey template function for your types (cf. the source). That will allow your type to use some other function rather than operator<:

template<> bool qMapLessThanKey<int>(const int &key1, const int &key2) 
{ 
    return key1 > key2;  // sort by operator> !
}

Nonetheless, std::map has the advantage that you can specify a different comparator per each map, while here you can't (all maps using your type must see that specialization, or everything will fall apart).

Saleh answered 4/7, 2013 at 7:33 Comment(1)
Random note: this is gone from Qt 6. Don't rely on this.Saleh
D
1

No, as far as i know QMap doesn't have that functionality it requires that it's key type to have operator<, so you are stuck with std::map if you really need that compare functionality.

Durfee answered 4/7, 2013 at 7:21 Comment(0)
I
1

QMap's key type must provide operator<(). QMap uses it to keep its items sorted, and assumes that two keys x and y are equal if neither x < y nor y < x is true.

In case, overload operator<().

Impetuous answered 4/7, 2013 at 7:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.