使用STL sort對字符串按字典序排序


使用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]]);
	}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM