C++手机通讯录排序

参考:https://www.cnblogs.com/lhwblog/p/6486036.html

Qt 4.8.4 vs2008

#include <QtGui/QApplication>

#include <qlocale.h>
#include <iostream>
#include <string>
#include <locale>
#include <vector>
#include <algorithm>
#include <QTableView>
#include <QTextCodec>
#include <Windows.h>

using namespace std;

struct CONTACT_Info
{
std::wstring name; // 名字
std::wstring addr; // 住址
};

static std::string WideToAnsi(std::wstring w)
{
char tmp[4096] = {0};

WideCharToMultiByte(CP_ACP, 0, w.c_str(), -1, tmp, 4096, NULL, NULL);

return std::string(tmp);
}

static const char *ZH_CN_LOCALE_STRING = "Chinese_china";
static const locale zh_CN_locale = locale(ZH_CN_LOCALE_STRING);
static const collate<char>& zh_CN_collate = use_facet<collate<char> >(zh_CN_locale);

bool zh_CN_bigger_than(const CONTACT_Info& s1, CONTACT_Info& s2)
{
std::string name1 = WideToAnsi(s1.name);
std::string name2 = WideToAnsi(s2.name);

const char *pb1 = name1.data();
const char *pb2 = name2.data();

return (zh_CN_collate.compare(pb1, pb1+name1.size(), pb2, pb2+name2.size()) < 0);
}

int main(int argc, char *argv[])
{
QApplication a(argc, argv);

QTextCodec::setCodecForTr(QTextCodec::codecForLocale());

//也可以使用QList,不能用std::list

vector<CONTACT_Info> v;


CONTACT_Info aa;
aa.name = L"第四一";
aa.addr = L"明";
v.push_back(aa);

CONTACT_Info xx;
xx.name = L"阿明";
xx.addr = L"明";
v.push_back(xx);

xx.name = L"周星星";
xx.addr = L"星星";
v.push_back(xx);

CONTACT_Info dd;
dd.name = L"第四一二三";
dd.addr = L"三";
v.push_back(dd);

CONTACT_Info bb;
bb.name = L"第一";
bb.addr = L"二";
v.push_back(bb);

CONTACT_Info cc;
cc.name = L"第叁";
cc.addr = L"六";
v.push_back(cc);

CONTACT_Info ee;
ee.name = L"长河";
ee.addr = L"六";
v.push_back(ee);

CONTACT_Info ff;
ff.name = L"大漠";
ff.addr = L"沙漠";
v.push_back(ff);

cout << "locale name: " << zh_CN_locale.name()<< endl;
std::sort(v.begin(), v.end(), zh_CN_bigger_than);

return a.exec();
}

原文地址:https://www.cnblogs.com/zhangxuan/p/8203230.html