C++primer5th课后题12.26、12.28

习题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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值