zoukankan      html  css  js  c++  java
  • 用insert重写单词计数程序

    int main (int argc, char* argv[])
    {
        std::ios::sync_with_stdio (false);
        //忽略列表
        setexclude = { "fuck", "damn" };
        string word;
        map< string, size_t> word_count;
        while (cin >> word) {
            //大小写不敏感, 全部转换为小写
            for (auto &ch : word)
                ch = tolower (ch);
            //只输入忽略列表中不在的单词
            if (exclude.find (word) == exclude.end ()) {
                //ret的类型是pair< map< string, size_t> ::iterator, bool>
                auto ret = word_count.insert (make_pair(word, 1));
                if (!ret.second)
                    //ret.first是一个word_count的迭代器
                    //ret.first->解引用
                    //++ret.first->second迭代器指向的计数器++
                    ++ret.first->second;
            }
        }
        for (auto it = word_count.cbegin (); it != word_count.cend (); ++it) {
            cout << "The " << it-> first << " has appered ";
            cout << it-&gtsecond << ((it-> second > 1) ? " times" : " time") << endl;
        }
        return 0;
    }

    或者直接:
    while (cin >> word)
            ++word_count.insert ({ word, 0 }).first->second;
    C++博大精深, 由此可见一斑.
  • 相关阅读:
    基本sql查询语句练习
    SZU:J38 Number Base Conversion
    SZU:B54 Dual Palindromes
    SZU:A66 Plastic Digits
    HOJ:2031 进制转换
    SZU:G34 Love code
    SZU:A25 Favorite Number
    Vijos:P1001谁拿了最多奖学金
    SZU:A26 Anagram
    SZU:A12 Jumping up and down
  • 原文地址:https://www.cnblogs.com/wuOverflow/p/4098730.html
Copyright © 2011-2022 走看看