C语言程序设计:按字典序排列文本
C语言程序设计:按字典序排列文本
问题描述
对分行输入的若干字符串按字典序(由小到大)进行排序并输出。
输入形式
控制台输入多行字符串,各个字符串可能含有空格。
输出形式
输出按字典序(由小到大)进行排序后的字符串。
样例输入
zftr fhoenf hefe afe geg
样例输出
afe geg fhoenf hefe zftr
样例说明
输入多行字符串:
zftr fhoenf hefe afe geg
输出字典序的字符串为:
afe geg fhoenf hefe zftr
解题思路
- 读入多行字符串,使用
getline()函数读入每一行字符串,并存储到vector中; - 对存储字符串的
vector进行排序,使用sort()函数,并传入自定义比较函数; - 输出排序后的字符串。
注意事项
- 使用
getline()函数读入字符串时,要注意空格的处理,需要使用getline(cin, str)函数,而不能使用cin >> str; - 自定义比较函数需要按照字典序进行比较,可以使用C++的字符串比较函数
strcmp()进行字符串的比较。
参考代码
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
int main() {
vector<string> strVec;
string str;
while (getline(cin, str)) {
strVec.push_back(str);
}
sort(strVec.begin(), strVec.end(), [](const string& str1, const string& str2) {
return strcmp(str1.c_str(), str2.c_str()) < 0;
});
for (auto str : strVec) {
cout << str << endl;
}
return 0;
}
原文地址: https://www.cveoy.top/t/topic/omco 著作权归作者所有。请勿转载和采集!