统计并输出所读入的单词出现的次数
2013-08-03 19:55
302 查看
题目:编写程序统计并输出所读入的单词出现的次数。
解答:
可以建立一个map对象,保存所读入的单词及其出现次数(以单词为键,对应的值为单词的出现次数)。
对于map容器,如果下标所表示的键在容器中不存在,则添加新元素,利用这一特性可编写程序如下:
如要求使用insert函数代替下标运算,重写程序。
解答:
使用insert函数对map对象进行插入操作时,如果试图插入的元素所对应的键已经在容器中,则insert将不做任何操作。而且,带一个键-值pair形参的insert函数将返回一个pair对象,该对象包含一个迭代器和一个bool值,其中迭代器指向map中具有相应键的元素,而bool值则表示是否插入了该元素。
利用上述特点,可编写程序如下:
使用下标操作的程序更简洁,更容易编写和阅读,而insert函数的返回值的使用比较复杂。但是用insert函数可以避免使用下标操作所带来的副作用,即避免对新插入元素的不必要的值初始化,而且可以显示表示元素的插入(下标操作是隐式表示元素的插入),有其优点。
解答:
可以建立一个map对象,保存所读入的单词及其出现次数(以单词为键,对应的值为单词的出现次数)。
对于map容器,如果下标所表示的键在容器中不存在,则添加新元素,利用这一特性可编写程序如下:
//通过建立map对象保存所读入的单词及其出现次数, //统计并输出所读入的单词出现的次数 #include<iostream> #include<map> #include<string> using namespace std; int main() { map<string , int> wordCount; string word; //读入单词并统计其出现次数 cout<<"Enter some words(Ctrl+Z to end):" <<endl; while(cin>>word) ++wordCount[word]; //word的出现次数加1 //输出结果 cout<<"word\t\t"<<"times"<<endl; for(map<string , int>::iterator iter = wordCount.begin() ; iter != wordCount.end() ; ++iter) cout<<(*iter).first<<"\t\t" <<(*iter).second<<endl; return 0; }
如要求使用insert函数代替下标运算,重写程序。
解答:
使用insert函数对map对象进行插入操作时,如果试图插入的元素所对应的键已经在容器中,则insert将不做任何操作。而且,带一个键-值pair形参的insert函数将返回一个pair对象,该对象包含一个迭代器和一个bool值,其中迭代器指向map中具有相应键的元素,而bool值则表示是否插入了该元素。
利用上述特点,可编写程序如下:
//通过建立map对象保存所读入的单词及其出现次数, //统计并输出所读入的单词出现的次数。 //其中使用insert函数代替下标操作 #include<iostream> #include<map> #include<utility> #include<string> using namespace std; int main() { map<string , int> wordCount; string word; //读入单词并统计其出现次数 cout<<"Enter some words(Ctrl+z to end):" <<endl; while(cin>>word) { //插入元素<word , 1> pair<map<string , int>::iterator , bool> ret = wordCount.insert(make_pair(word , 1)); if(!ret.second) //该单词已在容器中存在 ++ret.first->second; //将该单词的出现次数加1 } //输出结果 cout<<"word\t\t"<<"times"<<endl; for(map<string , int>::iterator iter = wordCount.begin() ; iter != wordCount.end() ; ++iter) cout<<(*iter).first<<"\t\t" <<(*iter).second<<endl; return 0; }
使用下标操作的程序更简洁,更容易编写和阅读,而insert函数的返回值的使用比较复杂。但是用insert函数可以避免使用下标操作所带来的副作用,即避免对新插入元素的不必要的值初始化,而且可以显示表示元素的插入(下标操作是隐式表示元素的插入),有其优点。
相关文章推荐
- 《C++ Primer》学习笔记:map容器insert操作的使用——编写程序统计并输出所读入的单词出现的次数
- java实现读取一篇英文文章,统计其中每个单词出现的次数并排序输出
- C++从一个文件中统计所有出现过的单词,并按次数从大到小输出
- 编写一个小程序,从标准输入读入一系列string对象,寻找连续重复出现的单词。程序应该找出满足一下条件的单词:该单词的后面紧接着再次出现自己本身。跟踪重复次数最多的单词及其重复次数,输出.
- Java实现读取键盘输入保存到txt文件,再统计并输出每个单词出现次数的方法
- 设计相应的数据结构和算法,尽量高效的统计一片英文文章(总单词数目)里出现的所有英文单词, * 按照在文章中首次出现的顺序打印输出该单词和它的出现次数。
- 编写一个小程序,从标准输入读入一系列string对象,寻找连续重复出现的单词。程序应该找出满足一下条件的单词:该单词的后面紧接着再次出现自己本身。跟踪重复次数最多的单词及其重复次数,输出.
- 统计输出某个文件中每个单词出现的次数
- Linux作业(三)-shell统计某文章中出现频率最高的N个单词并排序输出出现次数
- 统计单词出现的次数并按单词出现的次数顺序输出单词及其次数
- 统计海量文章内容中出现次数前K大的单词并输出(完整实现)
- 统计单词出现的次数并按单词出现的次数顺序输出单词及其次数
- Linux作业(三)-shell统计某文章中出现频率最高的N个单词并排序输出出现次数
- Java实现 统计单词出现的次数并按照单词频率从高到低输出
- 统计并输出英语短文中单词出现的次数
- 针对一个文件 统计其中的单词和字符数 找出文件中出现次数最多的单词数 将文件中出现的单词按频率进行排序并输出
- java 读取键盘输入到txt文件,统计每个单词出现的次数并输出
- 统计字符串”abadcdffbaeba”中每个字符出现了多少次,按次数排序并输出
- 统计一篇英文文件中,单词出现的次数,并按单词的长度进行排序
- C# 实现统计字符串中不同单词的出现次数【百度笔试题】