先介绍一下函数对象
下面直接定义一个用于比较的函数对象类
///file Compare.h
#pragma once
class Person;
enum EnumCompType
{
ASC,
DESC,
};
enum EnumCompField
{
ECF_Name,
ECF_Phone,
};
class Compare
{
public:
Compare(EnumCompType etype, EnumCompField eField);
bool operator() (const Person *, const Person *);
private:
EnumCompType m_eCompType;
EnumCompField m_eCompField;
};
///file Compare.cpp
#include "Compare.h"
#include "Person.h"
#include <QLocale>
#include <QCollator>
Compare::Compare(EnumCompType etype, EnumCompField eField)
:m_eCompType(etype)
,m_eCompField(eField)
{
}
bool Compare::operator()(const Person *pP1, const Person *pP2)
{
QLocale loc(QLocale::Chinese, QLocale::China);
QCollator qcol(loc);
int nResult = 0;
QString str1;
QString str2;
switch (m_eCompField)
{
case ECF_Name:
str1 = QString::fromLocal8Bit(pP1->GetName().c_str());
str1 = QString::fromLocal8Bit(pP2->GetName().c_str());
break;
case ECF_Phone:
str1 = QString::fromLocal8Bit(pP1->GetPhone().c_str());
str1 = QString::fromLocal8Bit(pP2->GetPhone().c_str());
break;
default:
break;
}
nResult = qcol.compare(str1, str2);
if (ASC == m_eCompType)
return nResult < 0 ? true : false;
else
return nResult < 0 ? false : true;
return false;
}
其中 Person 定义如下:
///file Person.h
#pragma once
#include <string>
class Person
{
public:
Person();
Person(std::string, std::string);
Person(Person &other);
~Person();
const std::string GetName() const { return m_strName; }
const std::string GetPhone() const { return m_strPhone; }
private:
std::string m_strName;
std::string m_strPhone;
};
///file Person.cpp
#include "Person.h"
Person::Person()
{
}
Person::Person(std::string strName, std::string strPhone)
:m_strName(strName)
,m_strPhone(strPhone)
{
}
Person::Person(Person & other)
{
this->m_strName = other.m_strName;
this->m_strPhone = other.m_strPhone;
}
Person::~Person()
{
}
随后对于给定的 QList<Person>
,可以直接排序
/// mian.cpp
#include <QtCore/QCoreApplication>
#include "Person.h"
#include "Compare.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QList<Person *> lstPerson;
Person p1("a", "123456789");
Person p2("b", "23456789");
Person p3("c", "3456789");
Person p4("d", "456789");
Person p5("e", "56789");
Person p6("f", "6789");
Person p7("g", "789");
Person p8("h", "89");
Person p9("i", "9");
lstPerson.append(&p4);
lstPerson.append(&p6);
lstPerson.append(&p9);
lstPerson.append(&p3);
lstPerson.append(&p7);
lstPerson.append(&p2);
lstPerson.append(&p1);
lstPerson.append(&p5);
lstPerson.append(&p8);
auto begin = lstPerson.begin();
auto end = lstPerson.end();
//??? Compare 是否会做 插入 或 删除操作 导致 end 失效呢???
qSort(begin, end, Compare(ASC, ECF_Name));
return a.exec();
}