我将来自正则表达式匹配的结果存储在unordered_map中。std :: cout子匹配m [1] .str()和m [2] .str()正确显示了对键值。虽然当我将它们存储在unordered_map中时,我总是会收到一个异常报告,指出未找到密钥,这是代码:boost::unordered::unordered_map<std::string, std::string>loadConfigFile(std::string pathToConfFile) throw(std::string){ std::fstream fs; fs.open(pathToConfFile.c_str()); if(!fs) throw std::string("Cannot read config file."); boost::unordered::unordered_map<std::string, std::string> variables; while(!fs.eof()) { std::string line; std::getline(fs, line); //std::cout << line << std::endl; boost::regex e("^(.+)\\s*=\\s*(.+)"); boost::smatch m; //This creates a boost::match_results if(boost::regex_match(line, m, e)){ std::cout << m[1].str() << " " << m[2].str() << std::endl; variables[m[1].str()] = m[2].str(); } } std::cout << variables.at(std::string("DEPOT_PATH")) << std::endl; //Here I get the exception return variables;}DEPOT_PATH是配置文件中“变量”的名称。 std :: cout 有任何想法吗? 最佳答案 您放置在无序映射中的键很可能包含空格(在输出时看不到键),因此以后找不到。在您的正则表达式^(.+)\\s*=\\s*(.+)中,第一个(.+)会贪婪地匹配尽可能多的字符,包括前导和尾随空格。后面的\\s*始终匹配一个空字符串。为防止这种情况,可以将(\\S+)仅用于非空白,或将非贪婪的(.+?)用于。顺便说一句,while (!fs.eof())是错误的。请改用while (std::getline(fs, line)) {...}。关于c++ - 使用std::string键从boost::unordered::unordered_map恢复值时出错,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15000959/
10-11 23:06
查看更多