題目描述 給定n個(gè)字符串,請(qǐng)對(duì)n個(gè)字符串按照字典序排列。 輸入描述: 輸入第一行為一個(gè)正整數(shù)n(1≤n≤1000),下面n行為n個(gè)字符串(字符串長(zhǎng)度≤100),字符串中只含有大小寫字母。
輸出描述: 數(shù)據(jù)輸出n行,輸出結(jié)果為按照字典序排列的字符串。 (注意:元素可以重復(fù))
輸入例子: 9 cap to cat card two too up boat boot
輸出例子: boat boot cap card cat to too two up
解答:#include <iostream>#include <vector>#include <string>#include <algorithm>using namespace std;int main(){ string str; int n; vector<string>v; while(cin>>n) { v.clear(); while(n>=1) { getline(cin,str); v.push_back(str); --n; } getline(cin,str); v.push_back(str); vector<string>::iterator it1=v.begin(); ++it1; sort(it1,v.end()); vector<string>::iterator it=v.begin(); ++it; for(;it!=v.end();it++) { cout<<*it<<endl; } } return 0;}解法二://當(dāng)元素加入set中后,已經(jīng)排好序#include <iostream>#include <string>#include <set>using namespace std;int main(){ string s; multiset<string> sset; int n; cin >> n; while (n-- && cin >> s) sset.insert(s); for (auto &t : sset) cout << t << endl; return 0;}新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注