C++ 按键对实际QMap排序
我有C++ 按键对实际QMap排序,c++,qt,sorting,qtcore,qmap,C++,Qt,Sorting,Qtcore,Qmap,我有QMap。我需要使用自然比较按键排序。 我有: std::map=c.toStdMap(); std::sort(map.begin()、map.end()、strnatcmp1); 然而,这甚至不编译。即使是这样,据我所知,它也会对我的原始QMap的副本进行排序 有没有办法使用提供的比较键功能按键对我的QMap进行排序?您可以采取以下几种方法: 将QString转换为整数后,将键存储为整数 您可以对std::map使用compare类: 您可以尝试使用QMap用于比较的speciali
QMap
。我需要使用自然比较按键排序。
我有:
std::map=c.toStdMap();
std::sort(map.begin()、map.end()、strnatcmp1);
然而,这甚至不编译。即使是这样,据我所知,它也会对我的原始QMap
的副本进行排序
有没有办法使用提供的比较键功能按键对我的
QMap
进行排序?您可以采取以下几种方法:
- 将
转换为整数后,将键存储为整数QString
- 您可以对std::map使用compare类:
- 您可以尝试使用QMap用于比较的specialize
你为什么要这么做?!QMap是一棵红黑树,它已经按键排序了。如果键是QString,它将按词汇排序(1101234),但我需要自然比较(12341011)。在这种情况下,为什么不使用int作为键呢?因为QString在项目中已经无处不在。这个软件不是我写的
std::map<QString, MyClass*> map = c.toStdMap();
std::sort(map.begin(), map.end(), strnatcmp1<std::pair<QString, MyClass*>>);
#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 with std::map:";
for (auto item : std_map)
qDebug() << item.first;
return 0;
}
TEMPLATE = app
TARGET = main
QT = core
CONFIG += c++11
SOURCES += main.cpp
qmake && make && ./main
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"