編程題#7:字符串排序
來源: 北京大學在線程序評測系統POJ (Coursera聲明:在POJ上完成的習題將不會計入Coursera的最后成績。)
總時間限制: 1000ms 內存限制: 1024kB
描述
請按照要求對輸入的字符串進行排序。
#include <iostream> #include <string> #include <list> using namespace std;class A{ private:string name; public:A(string n) :name(n){}friend bool operator < (const class A& a1, const class A &a2);friend bool operator == (const class A &a1, const class A &a2){if (a1.name.size() == a2.name.size())return true;elsereturn false;}friend ostream & operator << (ostream &o, const A &a){o << a.name;return o;}string get_name() const{return name;}int get_size() const{return name.size();} }; // 在此處補充你的代碼 int main(int argc, char* argv[]) {list<A> lst;int ncase, n, i = 1;string s;cin >> ncase;while (ncase--){cout << "Case: "<<i++ << endl;cin >> n;for (int i = 0; i < n; i++){cin >> s;lst.push_back(A(s));}lst.sort();Show(lst.begin(), lst.end(), Print());cout << endl;lst.sort(MyLarge<A>());Show(lst.begin(), lst.end(), Print());cout << endl;lst.clear();}return 0; }
?
輸入
第一行是正整數T,表示測試數據的組數
每組測試數據輸入共兩行,
第一行是正整數N,表示字符串個數
第二行是N個字符串, 字符串間用空格分離
?
輸出
對于每組測試數據,先輸出一行:
Case: n
如對第一組數據就輸出Case: 1
第二行按照字符串長度從小到大排序之后輸出N個字符串,字符串之間以空格間隔(不會出現字符串長度相同的情況)
第三行按照字符串首字符ASCII碼序從小到大排序之后輸出N個字符串,字符串之間以空格間隔(不會出現字符串首字母相同的情況)
?
樣例輸入
2 4 a bnss ds tsdfasg 5 aaa bbbb ccccd sa q
?
樣例輸出
Case: 1 a ds bnss tsdfasg a bnss ds tsdfasg Case: 2 q sa aaa bbbb ccccd aaa bbbb ccccd q sa
1 #include <iostream> 2 #include <string> 3 #include <list> 4 using namespace std; 5 6 class A{ 7 private: 8 string name; 9 public: 10 A(string n) :name(n){} 11 friend bool operator < (const class A& a1, const class A &a2); 12 friend bool operator == (const class A &a1, const class A &a2){ 13 if (a1.name.size() == a2.name.size()) 14 return true; 15 else 16 return false; 17 } 18 friend ostream & operator << (ostream &o, const A &a){ 19 o << a.name; 20 return o; 21 } 22 string get_name() const{ 23 return name; 24 } 25 int get_size() const{ 26 return name.size(); 27 } 28 }; 29 // 在此處補充你的代碼 30 bool operator< (const A& a1, const A &a2) { 31 return a1.name.size() < a2.name.size(); 32 }; 33 34 template <class Iterator, class Function> 35 void Show(Iterator begin, Iterator end, Function print) { 36 for (Iterator iterator1 = begin; iterator1 != end; iterator1++) { 37 print(*iterator1); 38 } 39 }; 40 41 class Print { 42 public: 43 void operator()(const A &a) { 44 cout << a.get_name()<< " "; 45 } 46 }; 47 48 template <class A> 49 struct MyLarge { 50 inline bool operator()(const A &a1, const A &a2) { 51 return a1.get_name() < a2.get_name(); 52 } 53 }; 54 55 int main(int argc, char* argv[]) 56 { 57 list<A> lst; 58 int ncase, n, i = 1; 59 string s; 60 cin >> ncase; 61 while (ncase--){ 62 cout << "Case: "<<i++ << endl; 63 cin >> n; 64 for (int i = 0; i < n; i++){ 65 cin >> s; 66 lst.push_back(A(s)); 67 } 68 lst.sort(); 69 Show(lst.begin(), lst.end(), Print()); 70 71 cout << endl; 72 lst.sort(MyLarge<A>()); 73 Show(lst.begin(), lst.end(), Print()); 74 cout << endl; 75 lst.clear(); 76 } 77 return 0; 78 }
?