[Accelerated c++读书笔记]统计单词出现的行号

    This is a program to generate a cross-reference table that indicated where each word occurs in the input.

Here is the program( I think this is a good example to illustrate the subject which is modern of c++ design of this book:

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

vector<string> split(const string &s)
{
	vector<string> ret;
	typedef string::size_type string_size;
	string_size i= 0;
	while( i != s.size() && isspace(s[i])){
		++i;

		string_size j = i;
		while( j != s.size() && ! isspace(s[j]))
			++j;

		if( i != j )
		{
			ret.push_back( s.substr(i, j-i));
			i = j;
		}
	}
	return ret;
}

map<string, vector<int> > xref( istream& in, vector<string> find_words(const string&) = split)
{
	string line;
	int line_number = 0;
	map<string, vector<int> >ret;

	while( getline( in, line) )
	{
		++line_number;
		vector<string> words = find_words(line);

		for( vector<string>::const_iterator it = words.begin(); it != words.end(); ++it)
			ret[ *it ].push_back( line_number);
	}
	return ret;
}

int main()
{
	ifstream in("Paindrome.cpp");
	map<string,vector<int> > ret = xref(in);
	for( map<string, vector<int> > ::const_iterator it = ret.begin(); it != ret.end(); it++)
	{

		cout << it->first << " occurs on line(s) : ";
		vector<int>::const_iterator line_it = it->second.begin();

		cout << *line_it;
		++line_it;

		while( line_it != it->second.end())
		{
			cout<< ", " << *line_it;
			++line_it;
		}
		cout << endl;
	}
	return 0;
}

      In this program,  we begin by calling xref to build a data structure that contains the numbers of the lines on which each word appears.We use the default value for the function parameter,so this call to xref will use split to break the input into words. The rest of the program writes the contents of the data structure that xref returns.

     As you read the body of the for loop, remember that dereferencing a map iterator yields a value of type pair. The first element of the pair holds the(const) key, and the second element is the value associated with that key.

你可能感兴趣的:([Accelerated c++读书笔记]统计单词出现的行号)