59 lines
1.7 KiB
C++
59 lines
1.7 KiB
C++
#include<iostream>
|
||
#include<string>
|
||
#include<map>
|
||
int main()
|
||
{
|
||
int a = 0;
|
||
std::cout << "请输入单词:" << std::endl;
|
||
std::cout << "退出按ctrl+z后回车" << std::endl;
|
||
std::string word;
|
||
std::map<std::string, int>word_data;
|
||
while (std::cin >> word) {
|
||
word_data[word] = word_data[word] + 1;
|
||
a = a + 1;
|
||
}
|
||
std::map<std::string, int>::iterator mp_next = word_data.begin();
|
||
std::cout << "输入的单词个数:" << a << std::endl;
|
||
while (mp_next != word_data.end())
|
||
{
|
||
std::cout << mp_next->first << " 的出现次数:" << mp_next->second << std::endl;
|
||
mp_next++;
|
||
}
|
||
}
|
||
|
||
|
||
#include <iostream> // 引入标准输入输出流库
|
||
#include <string> // 引入字符串库
|
||
#include <map> // 引入map容器库
|
||
|
||
int main()
|
||
{
|
||
int a = 0; // 用于统计输入的单词总数
|
||
std::cout << "请输入单词:" << std::endl; // 提示用户输入单词
|
||
std::cout << "退出按ctrl+z后回车" << std::endl; // 提示用户如何结束输入
|
||
|
||
std::string word; // 定义一个字符串变量,用于存储单个单词
|
||
std::map<std::string, int> word_data; // 定义一个map容器,key为单词,value为单词出现的次数
|
||
|
||
// 循环读取用户输入的单词,直到用户输入结束(Ctrl+Z后回车)
|
||
while (std::cin >> word) {
|
||
word_data[word] = word_data[word] + 1; // 更新单词出现次数,若不存在则初始化为1
|
||
a = a + 1; // 每读取一个单词,计数器加1
|
||
}
|
||
|
||
// 定义一个迭代器,用于遍历map容器
|
||
std::map<std::string, int>::iterator mp_next = word_data.begin();
|
||
|
||
// 输出总的输入单词数量
|
||
std::cout << "输入的单词个数:" << a << std::endl;
|
||
|
||
// 遍历map容器,输出每个单词及其出现次数
|
||
while (mp_next != word_data.end())
|
||
{
|
||
std::cout << mp_next->first << " 的出现次数:" << mp_next->second << std::endl; // 输出单词和对应次数
|
||
mp_next++; // 移动迭代器到下一个元素
|
||
}
|
||
|
||
return 0; // 程序结束
|
||
}
|