QMap的默认排序是按照key的升序进行排序。
如果我们想改变QMap的key的排序规则,则需要提供operator<()
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.
Qt帮助文档给的例子:
#ifndef EMPLOYEE_H
#define EMPLOYEE_H
class Employee
{
public:
Employee() {}
Employee(const QString &name, const QDate &dateOfBirth);
...
private:
QString myName;
QDate myDateOfBirth;
};
inline bool operator<(const Employee &e1, const Employee &e2)
{
if (e1.name() != e2.name())
return e1.name() < e2.name();
return e1.dateOfBirth() < e2.dateOfBirth();
}
#endif // EMPLOYEE_H
也可以把operator<写成类成员函数。
自己写的一个例子:
在Qt中新建一个控制台程序:
main.cpp中
#include <QCoreApplication>
#include <QMap>
#include <QDebug>
class MyString
{
public:
explicit MyString(const QString &str_) : str(str_) {}
QString str;
//重载操作符
bool operator < (const MyString& other) const
{
return str > other.str;
}
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QMap<MyString,int> stringMap;
//初始化数据
//数据插入容器
stringMap.insert(MyString("aa"), 4);
stringMap.insert(MyString("bb"), 3);
stringMap.insert(MyString("cc"), 2);
stringMap.insert(MyString("dd"), 1);
QMapIterator<MyString, int> iter(stringMap);
while (iter.hasNext()) {
iter.next();
qDebug() << iter.key().str << ": " << iter.value() << Qt::endl;
}
return a.exec();
}
运行结果:
就变成了key是按照QString进行降序排列。
如果代码改成这样:
class MyString
{
public:
explicit MyString(const QString &str_) : str(str_) {}
QString str;
//重载操作符
bool operator < (const MyString& other) const
{
return str < other.str; //这里就改成小于号,QMap里的排序就成了升序和QMap<QString, int>默认排序一样了
}
};
我再写一个按照int降序排序的例子:
#include <QCoreApplication>
#include <QMap>
#include <QDebug>
class MyInt
{
public:
explicit MyInt(const int &value_) : value(value_) {}
int value;
//重载操作符
bool operator < (const MyInt& other) const
{
return value > other.value;
}
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QMap<MyInt, QString> intMap;
//初始化数据
//数据插入容器
intMap.insert(MyInt(1), QString("aa"));
intMap.insert(MyInt(2), QString("bb"));
intMap.insert(MyInt(3), QString("cc"));
intMap.insert(MyInt(4), QString("dd"));
QMapIterator<MyInt, QString> iter(intMap);
while (iter.hasNext()) {
iter.next();
qDebug() << iter.key().value << ": " << iter.value();
}
return a.exec();
}
运行结果:
以上只是为了让举例的代码简单明了,没有写成get和set的方式对类成员变量进行操作,在项目中建议写出get和set的方法对类成员变量进行操作。