习题12.26
int main()
{
allocator<string> alloc;
auto const p = alloc.allocate(100);
string *q = p;
string s;
while (cin >> s && q != p + 100)
alloc.construct(q++, s);
for (size_t i = 0; i < (q-p); i++)
cout << p[i] << " ";
cout << endl;
while (q != p)
alloc.destroy(--q);
alloc.deallocate(p, 100);
}
习题12.28
vector<string> text;
string key("the");
map<string, set<size_t>> ci;
string word_process(string const &word)//处理句末,.符号,及大小写
{
string ret;
for (auto i : word) {
if (!ispunct(i))
ret += tolower(i);
}
return ret;
}
void input_text(ifstream &in)
{
string line;
string::size_type column = 0;
while (getline(in, line)) {
column++;
text.push_back(line);
istringstream ist(line);
string word;
while (ist >> word)
ci[word_process(word)].insert(column);
}
}
void serch(string& key)
{
if (ci.find(key) != ci.end()) {
cout << "element “" << key << "” occurs " << ci[key].size() << " times" << endl;
for (auto i : ci[key])
cout << " (line " << i << ") " << text[i-1] << endl;
}
else {
cout << "not found this word" << endl;
}
}
void runQueries(ifstream &in)
{
input_text(in);
while (true) {
cout << "请输入要查询的单词(q--退出)" << endl;
cin >> key;
if (key == "q" || !(cin))
break;
serch(key);
}
}
int main(int argc, char **argv)
{
ifstream in;
if (!(in.open(argv[1]), in) || argc != 2) {
cerr << "无法打开文件!" << endl;
return EXIT_FAILURE;
}
runQueries(in);
return 0;
//显示所有单词及其行数
for (auto i : ci) {
cout << i.first << "出现在 ";
for (auto j : i.second)
cout << j << " ";
cout << "行" << '\n' << endl;
}
}