《Essential C++》系列笔记之第三章(泛型编程风格)之第七节(使用Map)

在这里插入图片描述
代码实践

#include <iostream>
using namespace std;
#include <string>
#include <map>
#include <fstream>

int Number_of_words(ifstream& ifs)
{
	if (!ifs)
	{
		cerr << "file open" << endl;
		return 0;
	}

	string words;
	map<string, int> twords;
	twords["Python/python"] = 0;
	while (ifs >> words)
	{
		//统计 Python 单词
		string sub1 = "Python";
		int index1 = 0;
		while ((index1 = words.find(sub1, index1)) < words.length())
		{
			index1++;
			twords["Python/python"]++;
		}

		//统计 python 单词
		string sub2 = "python";
		int index2 = 0;
		while ((index2 = words.find(sub2, index2)) < words.length())
		{
			index2++;
			twords["Python/python"]++;
		}

	}
	return twords["Python/python"];
}

int main()
{

	//map<string, int> words;

	words["hehe"] = 1;

	字数统计
	//string tword;
	//while (cin >> tword)
	//{
	//	words[tword]++;
	//	if (cin.get() == '\n')
	//	{
	//		break;
	//	}
	//}

	打印单字及其出现的次数
	//map<string, int>::iterator iter = words.begin();
	//for (; iter != words.end(); iter++)          //注意这里是end(),不是begin(),不要写错了
	//{
	//	cout << iter->first << ' ' << iter->second << endl;
	//}

	//检查是否key存在的三种方法
#if 0
	cout << "方法1" << endl;
	cout << words["hmj"] << endl;
#endif
#if 0
	cout << "方法2" << endl;
	//words["hmj"] = 1;
	map<string, int>::iterator it = words.find("hmj");
	if (it != words.end())
	{
		cout << "yes" << endl;
	}
	else
	{
		cout << "no" << endl;
	}


#endif
#if 0
	cout << "方法3" << endl;
	words["hmj"] = 10;
	words["hmj"] = 100;
	cout << words.count("hmj") << endl; //count在map中值为1或者0(感觉可以理解成bool类型)
#endif

	//统计ptyhon.txt中"python"与"Python"一共出现的次数
	ifstream ifs("python.txt");
	cout << "一共出现了:" << Number_of_words(ifs) << "次!" <<endl;

	system("pause");
	return 0;
}

今天还是20200311 STL太强了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值