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.
C++程序生成单词交叉引用表
本文介绍了一个使用现代C++设计原则的程序,该程序可以生成一个表,显示输入文本中每个单词出现的位置。通过调用xref函数并默认使用split函数将输入分解为单词,然后遍历每一行,将单词及其出现的行号存储到映射中。最后,程序输出映射的内容,展示每个单词在文本中的位置。
600

被折叠的 条评论
为什么被折叠?



