• 统计并输出所读入的单词出现的次数


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

    解答:

    可以建立一个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函数可以避免使用下标操作所带来的副作用,即避免对新插入元素的不必要的值初始化,而且可以显示表示元素的插入(下标操作是隐式表示元素的插入),有其优点。

  • 相关阅读:
    SQL性能优化:如何定位网络性能问题
    ORACLE 10升级到10.2.0.5 Patch Set遇到的内核参数检测失败问题
    Linux 僵尸进程查杀
    Linux 虚拟机网络适配器从E1000改为VMXNET3
    v$session中server为none与shared值解析
    SQL SERVER导出特殊格式的平面文件
    XtraBackup出现 Can't connect to local MySQL server through socket '/tmp/mysql.sock'
    CentOS 6.6安装Xtrabackup RPM提示缺少libev.so.4()
    SQL Server Replication 中关于视图的点滴
    ORA-00988: missing or invalid password(s)
  • 原文地址:https://www.cnblogs.com/heyonggang/p/3235166.html
Copyright © 2020-2023  润新知