使用string數組
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
bool cmp(string a,string b){
return a < b; //按字典序從小到大排列
}
int main(){
string s[3];
s[0] = "wu";s[1]="jia";s[2]="jun";
sort(s,s+3,cmp);
for(int i = 0;i < 3;i++){
cout << s[i]<<" ";
}
}
使用char二維數組(某些情況下string會超時)
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
char name[3][4] = {"wu","jia","jun"};//二維數組保存n個字符串
bool cmp(int a,int b){
return strcmp(name[a],name[b]) < 0;
}
int main(){
int arr[3] = {0,1,2};//與字符串數組下標一一對應
sort(arr,arr+3,cmp);//排列的實際是標號 ,這么做更快
for(int i = 0;i <3 ;i++){
printf("%s ",name[arr[i]]);
}
}