[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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值