C++ Primer 练习11.1 & 11.3.2

11.4

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

int main(int argc, char* argv[])
{
	map<string, size_t> word_count;
	set<string> exclude = { "the", "but", "and", "or", "an", "a" };
	string word;
	while (cin >> word) 
	{
		*word.begin() = tolower(*word.begin());
		if (ispunct(*word.rbegin()))
			word.pop_back();
		if (exclude.find(word) == exclude.end())
			++word_count[word];
	}
	for (const auto& w : word_count)
		cout << w.first << " occurs " << w.second << (w.second > 1 ? " times." : " time.") << endl;
	return 0;
}

11.20

#include<iostream>
#include<fstream>
#include<vector>
#include<list>
#include<map>
#include<set>
#include<string>
#include<cctype>
#include<utility>
#include<algorithm>
using namespace std;

int main(int argc, char* argv[])
{
	map<string, size_t> word_count;
	set<string> exclude = { "the", "but", "and", "or", "an", "a" };
	string word;
	while (cin >> word)
	{
		*word.begin() = tolower(*word.begin());
		if (ispunct(*word.rbegin()))
			word.pop_back();
		if (exclude.find(word) == exclude.end()) {
			//auto ret = word_count.insert({ word, 1 });
			//if (ret.second)
			//	++ret.first->second;
			++word_count.insert({ word,0 }).first->second;	//与上等价
		}
	}
	for (const auto& w : word_count)
		cout << w.first << " occurs " << w.second << (w.second > 1 ? " times." : " time.") << endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/Dzx1025/article/details/107162415