Does QMap support custom comparator functions?

£可爱£侵袭症+ 提交于 2019-12-23 07:47:26

问题


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?


回答1:


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).




回答2:


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.




回答3:


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<().



来源:https://stackoverflow.com/questions/17463889/does-qmap-support-custom-comparator-functions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!