【HJ14】字串排序
阿新 • • 發佈:2021-01-03
題目描述
給定n個字串,請對n個字串按照字典序排列。
輸入描述:
輸入第一行為一個正整數n(1≤n≤1000),下面n行為n個字串(字串長度≤100),字串中只含有大小寫字母。
輸出描述:
資料輸出n行,輸出結果為按照字典序排列的字串。
示例1
輸入
9
cap
to
cat
card
two
too
up
boat
boot
輸出
boat
boot
cap
card
cat
to
too
two
up
題解思路
使用 C++ sort 函式實現對字串的排序。
sort 函式定義如下:
// std::sort define in <algorithm>
// default (1)
template <class RandomAccessIterator>
void sort (RandomAccessIterator first, RandomAccessIterator last);
// custom (2)
template <class RandomAccessIterator, class Compare>
void sort (RandomAccessIterator first, RandomAccessIterator last, Compare comp);
Sorts the elements in the range [first,last) into ascending order.
程式碼實現
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
bool cmp(string a, string b)
{
return a < b;
}
int main()
{
int n;
cin >> n;
vector<string> strs;
string str;
for(int i = 0; i < n; ++i) {
cin >> str;
strs.push_back(str);
}
sort(strs.begin(), strs.end(), cmp);
for(int i = 0; i < n; ++i) {
cout << strs[i] << endl;
}
return 0;
}