参考文档:http://zisxks.com/2013/10/25/sort-Chinese-characters-in-cpp/
采用locate.注意事项:排序的名字,如果出现某一个人,出现在顶上,可能是因为排序的名字前面是带有空格的,CString 类型的 可以采用 Trim() ,去掉前后的空格。
有个问题就是对于中文的多音字问题,这个函数排序的多音字,一般都会按照字母靠前的,但也有一部分是按照后字母靠后的音,猜想可能是多音字有多个枚举类型,挑的是里面的第一个,也有可能,多音字都有固定的拼音(查询资料未果)。
1 #include <iostream> 2 #include <string> 3 #include <locale> 4 #include <vector> 5 #include <algorithm> 6 using namespace std; 7 // Linux g++ locale 名称: "zh_CN.utf" 8 // VC2010 locale 名称: "Chinese"或者"Chinese_china" 9 #ifdef _MSC_VER 10 static const char *ZH_CN_LOCALE_STRING = "Chinese_china"; 11 #else 12 static const char *ZH_CN_LOCALE_STRING = "zh_CN.utf8"; 13 #endif 14 static const locale zh_CN_locale = locale(ZH_CN_LOCALE_STRING); 15 static const collate<char>& zh_CN_collate = use_facet<collate<char> >(zh_CN_locale); 16 bool zh_CN_less_than(const string &s1, const string &s2){ 17 const char *pb1 = s1.data(); 18 const char *pb2 = s2.data(); 19 return (zh_CN_collate.compare(pb1, pb1+s1.size(), pb2, pb2+s2.size()) < 0); 20 } 21 int main(void){ 22 vector<string> v; 23 v.push_back("啊"); 24 v.push_back("阿"); 25 v.push_back("第一"); 26 v.push_back("第二"); 27 v.push_back("第贰"); 28 v.push_back("di"); 29 v.push_back("第三"); 30 v.push_back("liu"); 31 v.push_back("第叁"); 32 v.push_back("第四"); 33 v.push_back("abc"); 34 v.push_back("aa"); 35 cout << "locale name: " << zh_CN_locale.name()<< endl; 36 sort(v.begin(), v.end(), zh_CN_less_than); 37 for(vector<string>::const_iterator p = v.begin(); p != v.end(); ++p){ 38 cout << *p << endl; 39 } 40 return EXIT_SUCCESS; 41 }
对于单个的好友成员排序
1 module::UserInfoEntity user1,user2; 2 USES_CONVERSION; 3 user1.csName.Trim(); 4 user2.csName.Trim(); 5 const char* username1 = W2A(user1.csName); 6 const char* username2 = W2A(user2.csName); 7 return (UserListModule_Impl::zh_CN_collate.compare(username1, username1 + strlen(username1), username2, username2 + strlen(username2)) < 0); 8 }
对于群组的成员排序,一般都需要有群组的id ,所以需要重写排序的方法,使用时
应该用 ID 初始化一次 groupInfo.groupMemeberList.sort(CompareGroupMemberMethod(groupInfo.gId));
1 class CompareGroupMemberMethod 2 { 3 public: 4 CompareGroupMemberMethod(std::string gId) :m_comparegId(gId) {}; 5 6 public: 7 8 bool operator () (const std::string& code1, const std::string& code2) 9 { 10 module::GroupMemberInfo* pMemInfo1; 11 module::GroupMemberInfo* pMemInfo2; 12 pMemInfo1 = module::getGroupListModule()->getGMInfoBySId(m_comparegId, code1); 13 pMemInfo2 = module::getGroupListModule()->getGMInfoBySId(m_comparegId, code2); 14 15 if (pMemInfo1 != NULL && pMemInfo2 != NULL) 16 { 17 CString memberName1 = util::stringToCString(pMemInfo1->name); 18 CString memberName2 = util::stringToCString(pMemInfo2->name); 19 memberName1.Trim(); 20 memberName2.Trim(); 21 22 USES_CONVERSION; 23 const char* mebName1 = W2A(memberName1); 24 const char* mebName2 = W2A(memberName2); 25 return (UserListModule_Impl::zh_CN_collate.compare(mebName1, mebName1 + strlen(mebName1), mebName2, mebName2 + strlen(mebName2)) < 0); 26 } 27 28 return false; 29 }