C++11: unordered_map

来源:互联网 发布:解方程组软件 编辑:程序博客网 时间:2024/06/05 09:57
#include <unordered_map>#include <fstream>#include <iostream>#include <string>#include <sstream>void word_transform(std::ifstream &map_file, std::ifstream &input);std::unordered_map<std::string, std::string>         buildUnorderedmap(std::ifstream &map_file);const std::string& transform(const std::string &s,           const std::unordered_map<std::string, std::string> &m);int main(){        std::ifstream rule("rules.txt");        std::ifstream text("text.txt");        word_transform(rule, text);        return 0;}void word_transform(std::ifstream &map_file, std::ifstream &input){        auto trans_map = buildUnorderedmap(map_file);        std::string text;        while (std::getline(input, text)) {                std::istringstream stream(text);                std::string word;                bool firstword = true;                while (stream >> word) {                        if (firstword) {                                firstword = false;                        } else {                                std::cout << " ";                        }                        std::cout << transform(word, trans_map);                }                std::cout << std::endl;        }}std::unordered_map<std::string, std::string>        buildUnorderedmap(std::ifstream &map_file){        std::unordered_map<std::string, std::string> trans_map;        std::string key;        std::string value;        while (map_file >> key && std::getline(map_file, value)) {                if (value.size() > 1) {                        trans_map.insert({key, value.substr(1)});                }        }        return trans_map;}const std::string& transform(const std::string &s,          const std::unordered_map<std::string, std::string> &m){        auto map_it = m.find(s);        if (map_it != m.end()) {                return map_it->second;        } else {                return s;        }}
// from C++ primer 5th exercise 11.38(p.446)// g++ xx.cpp -std=c++11
0 0