php 字符串 字典序序排序,C++ 怎么实现字典序排序法,自然排序
C++ 如何實(shí)現(xiàn)字典序排序法,自然排序
類(lèi)似PHP的natcasesort函數(shù),整了一天沒(méi)有頭緒.
數(shù)組是vector
排序前:
[0]?=>?IMG0.png
[1]?=>?IMG3.png
[2]?=>?img1.png
[3]?=>?img10.png
[4]?=>?img12.png
[5]?=>?img2.png
排序后:
[0]?=>?IMG0.png
[1]?=>?img1.png
[2]?=>?img2.png
[3]?=>?IMG3.png
[4]?=>?img10.png
[5]?=>?img12.png
------解決方案--------------------
其實(shí)樓主的意思就是按數(shù)字大小排序唄??預(yù)處理的時(shí)候把數(shù)值部分摘出來(lái)作為排序的key。
------解決方案--------------------
定位到數(shù)字部分,讀取數(shù)字再比較?
bool?compare(const?string&?name1,?const?string&?name2)
{
int?num1,?num2;
sscanf(name1.c_str()+3,?"%d",?&num1);
sscanf(name2.c_str()+3,?"%d",?&num2);
return?num1?
}
------解決方案--------------------
sort(vector.begin(),vector.end(),[](const?string&a,const?string&b){return?a[3]<b[3];});泛型算法和lambda
------解決方案--------------------
直接添加到容器,自動(dòng)排序
------解決方案--------------------
引用:Quote: 引用:定位到數(shù)字部分,讀取數(shù)字再比較?
bool?compare(const?string&?name1,?const?string&?name2)
{
int?num1,?num2;
sscanf(name1.c_str()+3,?"%d",?&num1);
sscanf(name2.c_str()+3,?"%d",?&num2);
return?num1?
}
這樣就有點(diǎn)局域性了,不能確定后面一定是數(shù)字
那你倒是說(shuō)說(shuō)具體的規(guī)則啊,對(duì)于你舉的例子,以上那個(gè)比較規(guī)則應(yīng)該是夠了
------解決方案--------------------
std::sort(files.begin(),files.end(),?[](const?std::string&?a,?const?std::string&?b)
{
return?a.substr(3,std::string::npos)
});
------解決方案--------------------
簡(jiǎn)單的寫(xiě)了下?用的是qsort
#include?
#include?
#include?
char?data[6][10]={{"img0"},
{"img3"},
{"img1"},
{"img10"},
{"img12"},
{"img2"}};
int?cmp(const?void?*a,?const?void?*b)
{
char?*temp_a?=?(char?*)a;
char?*temp_b?=?(char?*)b;
//?如果兩個(gè)字符串的長(zhǎng)度不相等那么就把少的放前面
if(strlen(temp_a)!=?strlen(temp_b))
return?strlen(temp_a)-strlen(temp_b);
//?兩字符串相等,就升序
for(int?i=0;?i?
{
if(temp_a[i]!=temp_b[i])
return?temp_a[i]-temp_b[i];
}
}
int?main()
{
printf("排序前:\n");
for(int?i=0;?i?
printf("%s\n",?data[i]);
qsort(data,?6,?10*sizeof(char),?cmp);
printf("排序后:\n");
for(int?i=0;?i?
printf("%s\n",?data[i]);
return?0;
}
------解決方案--------------------
------解決方案--------------------
總結(jié)
以上是生活随笔為你收集整理的php 字符串 字典序序排序,C++ 怎么实现字典序排序法,自然排序的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 女生高冷网名141个
- 下一篇: app http routes.php,