zoukankan      html  css  js  c++  java
  • 统计并输出所读入的单词出现的次数

    题目:编写程序统计并输出所读入的单词出现的次数。

    解答:

    可以建立一个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		"<<"times"<<endl;
    	for(map<string , int>::iterator iter = wordCount.begin() ; iter != wordCount.end() ; ++iter)
    		cout<<(*iter).first<<"		"
    		    <<(*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		"<<"times"<<endl;
    	for(map<string , int>::iterator iter = wordCount.begin() ; iter != wordCount.end() ; ++iter)
    		cout<<(*iter).first<<"		"
    		    <<(*iter).second<<endl;
    
    	return 0;
    }
    

     使用下标操作的程序更简洁,更容易编写和阅读,而insert函数的返回值的使用比较复杂。但是用insert函数可以避免使用下标操作所带来的副作用,即避免对新插入元素的不必要的值初始化,而且可以显示表示元素的插入(下标操作是隐式表示元素的插入),有其优点。

  • 相关阅读:
    CSS position, z-index
    Js闭包函数
    .net 全局配置读取
    redis学习
    .net core websocket
    .net core 部署应用程序注意事项
    signalr网上学习资料
    Cocos Creator 中如果Node在"属性检查器"中active设置为false, 则 onLoad 不会执行
    SVN服务器搭建(一)
    IndentityServer4
  • 原文地址:https://www.cnblogs.com/heyonggang/p/3235166.html
Copyright © 2011-2022 走看看