字符串排序与sort()函数
程序示例
描述
给定 n 个字符串,请对 n 个字符串按照字典序排列。
数据范围:1≤n≤1000 ,字符串长度满足1≤len≤100
输入描述:
输入第一行为一个正整数n(1≤n≤1000),下面n行为n个字符串(字符串长度≤100),字符串中只含有大小写字母。
输出描述:
数据输出n行,输出结果为按照字典序排列的字符串。
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
bool comp(string a,string b){
return a<b;//升序排列
}
int main(){
int n;
cin>>n;
string str[n];
for(int i=0;i<n;i++){
cin>>str[i];
}
sort(str,str+n,comp);
for(int j=0;j<n;j++){
cout<<str[j]<<endl;
}
}
关于sort()函数
-
sort()函数位于头文件
-
sort()函数的两种常见语法
//对 [first, last) 区域内的元素做默认的升序排序
void sort (RandomAccessIterator first, RandomAccessIterator last);
//按照指定的 comp 排序规则,对 [first, last) 区域内的元素进行排序
void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);
-
两参数示例
#include <iostream> #include <algorithm> using namespace std; int main() { int a[20] = { 21,65,21,51,85,1,24,10 }; cout << "原数列:"; for (int i = 0; i < 20; i++) cout << a[i] <<" "; cout << endl; sort(a, a + 20);//a指向数组的首地址;sort的两个参数分别指向排序内容的首尾地址;默认为升序排列 cout << "排序后:"; for (int i = 0; i < 20; i++) cout <<a[i] << " "; }
输出
原数列:21 65 21 51 85 1 24 10 0 0 0 0 0 0 0 0 0 0 0 0 排序后:0 0 0 0 0 0 0 0 0 0 0 0 1 10 21 21 24 51 65 85
-
三参数示例
#include <iostream> #include <algorithm> #include <vector> using namespace std; //以普通函数的方式实现自定义排序规则 bool myfunction(int i, int j) { return i < j; }//升序排列 bool myfunction2(int i, int j) { return i > j; }//降序排列 int main() { vector<int> a{ 21,65,21,51,85,1,24,10 }; sort(a.begin(), a.begin() + 4,myfunction);//(21 21 51 65) 85 1 24 10 cout << "myfunction排序后:"; for (int i = 0; i < 8; i++) cout <<a[i] << " "; cout << endl; sort(a.begin()+4, a.begin() + 8, myfunction2);//21 21 51 65( 85 24 10 1)在第一次排序的基础上后4个数的排序 cout << "myfunction2排序后:"; for (int i = 0; i < 8; i++) cout << a[i] << " "; cout << endl; return 0; }
-
参考链接
C++ sort排序函数用法_浅然言而信的博客-CSDN博客_c++ sort排序
C++ sort()排序函数用法详解 (biancheng.net)