我将正则表达式匹配得到的结果存储在 unordered_map 中。 std::cout 子匹配 m[1].str() 和 m[2].str() 正确显示键值对。
虽然当我将它们存储在 unordered_map 中时,我总是会收到一个异常报告,指出找不到 key 。这是代码:
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 << m[1].str() 完美地显示了它,但在 unordered_map 中找不到。 有什么想法吗?
最佳答案
很可能,您放入无序映射中的键包含空格(输出时看不到),因此稍后找不到。
在您的正则表达式 ^(.+)\\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/