count words

主要涉及到map,vector和iterator.

1.统计每一个单词出现的次数

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

void main()
{
	string s;
	map<string,int> counters;
	while (cin >> s)
	{
		++ counters[s];
	}

	for (map<string,int>::const_iterator it = counters.begin();it!=counters.end();++it)
	{
		cout<<it->first<<"\t"<<it->second<<endl;
	}
}

2.统计每个单词出现在位置(哪一个行)。

#include <iostream>
#include <map>
#include <vector>
#include <string>
#include<ctype.h>
#include <algorithm>
using namespace std;

bool space(char c)
{
	return isspace(c);
}

bool not_space(char c)
{
	return !isspace(c);
}

//Slip function is to slip the line to a words vector
vector<string> split(const string& str)
{
	typedef string::const_iterator iter;
	vector<string> ret;
	iter i = str.begin();
	while (i!=str.end())
	{
		//ignore leading blanks
		i = find_if(i,str.end(),not_space);

		//find end of next word
		iter j = find_if(i,str.end(),space);

		//copy the characters in [i,j)
		if (i!=str.end())
		{
			ret.push_back(string(i,j)); //这里的i和j是迭代器,用string(i,j)就相当于截取了[i,j)之间的字符
		}
		i=j;
	}
	return ret;
}

//This function generate the line number vector for every words
map<string,vector<int>> xref(istream&in)
{
	string line;
	int line_number = 0;
	map<string,vector<int>> ret;

	//read the next line
	while (getline(in,line))
	{
		++line_number;

		//break the line into words
		vector<string> words = split(line);

		//remember that each word occurs on the current line
		for (vector<string>::const_iterator it=words.begin();it!=words.end();++it)
		{
			ret[*it].push_back(line_number);
		}
	}
	return ret;
}

void main()
{
	//call xref
	map<string,vector<int>> ret = xref(cin);

	//write the results
	for (map<string,vector<int>>::const_iterator it=ret.begin();it!=ret.end();++it)
	{
		//write the word
		cout<<it->first<<" occurs on lines(s): ";

		//write the occurs number
		vector<int>::const_iterator line_it = it->second.begin();
		do 
		{			
			cout<<" "<<*line_it;
			++line_it;
		} while (line_it !=it->second.end());
		cout<<endl;
	}
};


你可能感兴趣的:(count words)