使用std::string键从boost::无序::无序映射中恢复值时出错
Error recovering values from boost::unordered::unordered_map using std::string keys
我将从正则表达式匹配中获得的结果存储在一个无序映射中。std::cout子匹配m[1].str()和m[2].str(。
尽管当我将它们存储在一个无序映射中时,我总是会收到一个异常,报告没有找到密钥。这是代码:
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<lt;m[1].str()完美地显示了它,但在无序映射中找不到。有什么想法吗?
最有可能的是,您放在无序映射中的键包含空白(输出时看不到),因此以后找不到。
在正则表达式^(.+)\s*=\s*(.+)
中,第一个(.+)
将贪婪地匹配尽可能多的字符,包括前导和尾随空格。它后面的\s*
将始终与一个空字符串匹配。为了防止这种情况,您可以仅对非空白使用(\S+)
,或者使用非贪婪的(.+?)
。
顺便说一下,while (!fs.eof())
是错的。请改用while (std::getline(fs, line)) {...}
。
相关文章:
- 用C++将哈希表写入文件并从文件中恢复
- 递归无序映射
- c++找不到具有相同哈希的无序集合元素
- 正在将无序映射设置为无序映射的值
- 智能指针作为无序映射键,并通过引用进行比较
- 如何使用set实现无序数据结构?
- 如何写向量的无序向量集,即unordered_set<向量<向量<int>>集合?
- 如何禁用 CPU 的无序执行
- Opencv 恢复到比我设置的更高的分辨率
- 变量在使用赋值语句赋值后恢复为以前的值
- 在信号处理程序中捕获C++未处理的异常并恢复应用程序
- 删除所有字符串后如何恢复 QStringList?
- 当对套接字 send() 的同步调用由于连接另一端丢失而被阻止时,如何恢复?
- 从C++无序集合中高效提取元素
- 如何仅使用一次固定<<设置精度(2)?或者至少恢复到默认行为?
- "co_yield"是否可以在恢复协程时从调用方返回值?
- OpenSSL C API:如何在程序exec()之后恢复TLS连接?
- 打印无序映射的第二个元素,即集合
- 通过指针恢复对数组的引用.UB与否?
- 使用std::string键从boost::无序::无序映射中恢复值时出错