日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

n个字符串按照字典序排列

發布時間:2023/12/10 编程问答 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 n个字符串按照字典序排列 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

題目描述
給定n個字符串,請對n個字符串按照字典序排列。
輸入描述:
輸入第一行為一個正整數n(1≤n≤1000),下面n行為n個字符串(字符串長度≤100),字符串中只含有大小寫字母。

輸出描述:
數據輸出n行,輸出結果為按照字典序排列的字符串。

輸入例子:
9
cap
to
cat
card
two
too
up
boat
boot

輸出例子:
boat
boot
cap
card
cat
to
too
two
up

做這道題之前先來看一下C++中的庫函數sort():
STL里面有個sort函數,可以直接對數組排序,復雜度為n*log2(n)。sort()定義在在頭文件中。sort函數是標準模板庫的函數,已知開始和結束的地址即可進行排序,可以用于比較任何容器(必須滿足隨機迭代器),任何元素,任何條件,執行速度一般比qsort要快。另外,sort()是類屬函數,可以用于比較任何容器,任何元素,任何條件。具體事例如下:

1、sort(begin,end),表示一個范圍:

#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中一個改變排序順序的例子如下(降序):

#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; }

這個函數可以傳兩個參數或三個參數。第一個參數是要排序的區間首地址,第二個參數是區間尾地址的下一地址。也就是說,排序的區間是[a,b)。簡單來說,有一個數組int a[100],要對從a[0]到a[99]的元素進行排序,只要寫sort(a,a+100)就行了,默認的排序方式是升序。如需要對數組t的第0到len-1的元素排序,就寫sort(t,t+len);對向量v排序也差不多,sort(v.begin(),v.end());排序的數據類型不局限于整數,只要是定義了小于運算的類型都可以,比如字符串類string。

假設自己定義了一個結構體node:

struct node{int a;int b;double c; };

有一個node類型的數組node arr[100],想對它進行排序:先按a值升序排列,如果a值相同,再按b值降序排列,如果b還相同,就按c降序排列。就可以寫這樣一個比較函數:

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; //降序排列 }

那么現在就來做上面的題吧:

#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(); //這個要加上,不然會吃掉一個字符串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; }

總結

以上是生活随笔為你收集整理的n个字符串按照字典序排列的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。