错误从boost :: unordered :: unordered_map使用std :: string键恢复值
问题描述:
我存储在unordered_map从正则表达式匹配得到的结果。 std :: cout子匹配m [1] .str()和m [2] .str()正确显示对键值。错误从boost :: unordered :: unordered_map使用std :: string键恢复值
虽然当我把它们存储在一个unordered_map我总是得到一个异常的报告,关键是不found.This是代码:
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;
}
仓库路径是一个“变量”这个名字在配置文件。 std :: cout < < m [1] .str()完美显示,但未在unordered_map中找到。 任何想法?
答
最有可能的是,您在无序映射中放入的键包含空格(输出时看不到),因此稍后没有找到。
在你的正则表达式^(.+)\\s*=\\s*(.+)
中,第一个(.+)
会贪婪地匹配尽可能多的字符,包括前导和尾随空格。它后面的\\s*
将始终匹配一个空字符串。为防止出现这种情况,您只能将(\\S+)
用于非空白字符,或者使用非贪婪的(.+?)
。
顺便说一下,while (!fs.eof())
是错误的。改为使用while (std::getline(fs, line)) {...}
。
2双眼睛显然比一只眼睛好。 2小时努力修复错误,我需要刷新我的正则表达式的知识,非常感谢:) – 2013-02-21 11:51:56