c++ associative container: map and set

来源:互联网 发布:二年级体测数据 编辑:程序博客网 时间:2024/06/01 10:36
#include <map>#include <set>#include <string>#include <iostream>#include <algorithm>#include <functional>#include <locale>void rightTrimPunct(std::string &str){        std::locale locl("C");        if (!str.empty()) {                if (std::ispunct(str.back(), locl)) {                        str.pop_back();                }        }}void toUpper(std::string &str){        std::locale locl("C");        std::transform(str.begin(), str.end(), str.begin(),                        std::bind(std::toupper<char>, std::placeholders::_1, locl));}int main(){        std::map<std::string, size_t> word_count;        std::set<std::string> exclude = {"The", "But", "Or", "An", "A",                                         "the", "but", "or", "an", "a"};        std::string word;        while (std::cin >> word) {                rightTrimPunct(word);                toUpper(word);                if (!word.empty() && exclude.find(word) == exclude.end())                        ++word_count[word];        }           for (const auto &w : word_count) {                std::cout << w.first << " occurs " << w.second                          << ((w.second > 1) ? " times" : " time") << std::endl;        }        return 0;}

From C++ primer 5th Excercise 11.4 (p.422)

g++ *.cpp -std=c++11//gcc 4.9.2
0 0
原创粉丝点击