n个字符串按照字典序排列
題目描述
給定n個(gè)字符串,請(qǐng)對(duì)n個(gè)字符串按照字典序排列。
輸入描述:
輸入第一行為一個(gè)正整數(shù)n(1≤n≤1000),下面n行為n個(gè)字符串(字符串長(zhǎng)度≤100),字符串中只含有大小寫(xiě)字母。
輸出描述:
數(shù)據(jù)輸出n行,輸出結(jié)果為按照字典序排列的字符串。
輸入例子:
9
cap
to
cat
card
two
too
up
boat
boot
輸出例子:
boat
boot
cap
card
cat
to
too
two
up
做這道題之前先來(lái)看一下C++中的庫(kù)函數(shù)sort():
STL里面有個(gè)sort函數(shù),可以直接對(duì)數(shù)組排序,復(fù)雜度為n*log2(n)。sort()定義在在頭文件中。sort函數(shù)是標(biāo)準(zhǔn)模板庫(kù)的函數(shù),已知開(kāi)始和結(jié)束的地址即可進(jìn)行排序,可以用于比較任何容器(必須滿足隨機(jī)迭代器),任何元素,任何條件,執(zhí)行速度一般比qsort要快。另外,sort()是類(lèi)屬函數(shù),可以用于比較任何容器,任何元素,任何條件。具體事例如下:
1、sort(begin,end),表示一個(gè)范圍:
#include <algorithm> #include <iostream>using namespace std; int main() {int a[10] = { 2, 4, 1, 23, 5, 76, 0, 43, 24, 65 };for (int i = 0; i<10; i++)cout << a[i] << endl;sort(a, a + 10);cout << endl;for (int i = 0; i<10; i++)cout << a[i] << endl;return 0; }注意:缺省是升序排序。sort中一個(gè)改變排序順序的例子如下(降序):
#include <algorithm> #include <iostream>using namespace std;bool cmp(int a, int b) {return a > b; } int main() {int a[10] = { 2, 4, 1, 23, 5, 76, 0, 43, 24, 65 };for (int i = 0; i<10; i++)cout << a[i] << endl;sort(a, a + 10, cmp);cout << endl;for (int i = 0; i<10; i++)cout << a[i] << endl;return 0; }這個(gè)函數(shù)可以傳兩個(gè)參數(shù)或三個(gè)參數(shù)。第一個(gè)參數(shù)是要排序的區(qū)間首地址,第二個(gè)參數(shù)是區(qū)間尾地址的下一地址。也就是說(shuō),排序的區(qū)間是[a,b)。簡(jiǎn)單來(lái)說(shuō),有一個(gè)數(shù)組int a[100],要對(duì)從a[0]到a[99]的元素進(jìn)行排序,只要寫(xiě)sort(a,a+100)就行了,默認(rèn)的排序方式是升序。如需要對(duì)數(shù)組t的第0到len-1的元素排序,就寫(xiě)sort(t,t+len);對(duì)向量v排序也差不多,sort(v.begin(),v.end());排序的數(shù)據(jù)類(lèi)型不局限于整數(shù),只要是定義了小于運(yùn)算的類(lèi)型都可以,比如字符串類(lèi)string。
假設(shè)自己定義了一個(gè)結(jié)構(gòu)體node:
struct node{int a;int b;double c; };有一個(gè)node類(lèi)型的數(shù)組node arr[100],想對(duì)它進(jìn)行排序:先按a值升序排列,如果a值相同,再按b值降序排列,如果b還相同,就按c降序排列。就可以寫(xiě)這樣一個(gè)比較函數(shù):
bool cmp(node x,node y) {if(x.a!=y.a) return x.a //升序排列if(x.b!=y.b) return x.b>y.b; //降序排列return return x.c>y.c; //降序排列 }那么現(xiàn)在就來(lái)做上面的題吧:
#include <algorithm> #include <iostream> #include <string>using namespace std;bool cmp(string a, string b) {return a < b; } int main() {int num;while(cin >> num){getchar(); //這個(gè)要加上,不然會(huì)吃掉一個(gè)字符串string* s = new string[1000];for (int i = 0; i < num; i++){getline(cin,s[i],'\n');}sort(s,s+num,cmp);for (int i = 0; i < num; i++){cout << s[i] << endl;}} return 0; }或者:
#include <vector> #include <iostream> #include <string> #include <algorithm>using namespace std;bool cmp(string a, string b) {return a < b; }int main() {int num;string str;vector<string> v;while (cin >> num){while (num--){cin >> str;v.push_back(str);}sort(v.begin(),v.end(),cmp);cout << endl;for (int i = 0; i < v.size(); i++){cout << v[i] << endl;}}return 0; }總結(jié)
以上是生活随笔為你收集整理的n个字符串按照字典序排列的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: gmssl编译linux,linux 编
- 下一篇: 软考 | 软考高项论文该如何去写?