map映射底层是用红黑树来实现的,可以使映射有序,所以此题就可以使用map,将字符串逐个添加至映射中,最后按序输出即可,即省去了对字符串进行存储,也省去了排序的步骤
#include <cstdio> #include <iostream> #include <string> #include <map> using namespace std; int main() { int n; while(scanf("%d", &n) != EOF) { getchar();//吸收换行符 map<int, string> mymap;//定义map映射 int i = 0; for(i; i < n; i++) { string str; getline(cin, str); if(str == "stop") break; int m = str.size() ; mymap[m] = str; //因为本题要求按字符串长度排序,map映射是有序的,只要将字符串长度设为first, 字符串本身设为second,就可以在map映射中按字符串长度进行排序 } map<int, string>::iterator it; /*按顺序输出映射中的second即可*/ for(it = mymap.begin(); it != mymap.end() ; it++) { cout <<it->second<<endl; } } return 0; }