c++ - Sort actual QMap by key -
c++ - Sort actual QMap by key -
i have qmap<qstring, myclass*>
. need sort key using natural comparison. do:
std::map<qstring, myclass*> map = c.tostdmap(); std::sort(map.begin(), map.end(), strnatcmp1<std::pair<qstring, myclass*>>);
however, not compile. , if did, far understand, sort copy of original qmap
.
is there way sort qmap
key function comparing keys provided?
you have several appoaches take:
store keys integers after converting qstring
integer.
you can utilize compare class std::map as per example:
you can seek utilize specialize this template function qmap uses comparison.
main.cpp#include <qmap> #include <qdebug> #include <map> struct str_num_compare { bool operator() (const qstring& lhs, const qstring& rhs) const {return lhs.toint()<rhs.toint();} }; int main() { qstringlist stringlist{"1", "10", "11", "2", "3", "4"}; qmap<int, qstring> map; foreach (const qstring &string, stringlist) map.insert(string.toint(), string); qdebug() << "integer key approach:" << map; std::map<qstring, qstring, str_num_compare> std_map; foreach (const qstring &string, stringlist) std_map[string] = string; qdebug() << "qstring key approach std::map:"; (auto item : std_map) qdebug() << item.first; homecoming 0; }
main.pro template = app target = main qt = core config += c++11 sources += main.cpp
build , run qmake && create && ./main
output integer key approach: qmap((1, "1")(2, "2")(3, "3")(4, "4")(10, "10")(11, "11")) qstring key approach: "1" "2" "3" "4" "10" "11"
c++ qt sorting qtcore qmap
Comments
Post a Comment