题解:B4267 [朝阳区小学组 2019] word
Yi_chen123 · · 题解
前置知识
istringstream 是一种特殊的输入流对象,即字符串输入流,它的使用与正常的输入流相差不大,只是把输入数据的地方改为了一个字符串内部。\
下面是一个例子(不完整代码):
string s = "114514 hello";
istringstream iss(s); //一个关联字符串 s 的字符串输入流
int n; string s1;
iss >> n >> s1; //使用字符串输入流进行字符串内的输入
cout << n << endl << s1;
输出结果如下:
114514
hello
思路
我们首先使用 getline() 函数以获取整行的字符串,再使用 istringstream 不断读取这一行以空格分隔的单词,使用一个 vector 存放单词,再使用一个变量 cnt 记录单词出现的次数,将 vector 排序,最后将结果输出即可。
完整代码
#include<bits/stdc++.h>
using namespace std;
int main(){
string s1;
while(getline(s1, cin)){
vector<string> words;
string word;
istringstream iss(s1);
int cnt = 0;
while(iss >> word){ //重复读取一行中的若干个单词,并将单词存储至 vector 中
words.push_back(word);
++cnt;
}
sort(words.begin(), words.end());
cout << cnt << ' ';
for(int i = 0; i < words.size(); ++i) cout << words[i] << ' ';
cout << endl;
}
return 0;
}