使用std::string键从boost::无序::无序映射中恢复值时出错

Error recovering values from boost::unordered::unordered_map using std::string keys

本文关键字:无序 恢复 出错 映射 string 键从 boost 使用 std      更新时间:2023-10-16

我将从正则表达式匹配中获得的结果存储在一个无序映射中。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)) {...}