c++ - 使用 std::string 键从 boost::unordered::unordered_map 恢复值时出错

标签 c++ boost boost-regex boost-unordered

我将正则表达式匹配得到的结果存储在 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/

相关文章:

c++ - 如何使用 boost::iostreams 将 bash 脚本转换为 C++

c++ - 如何包含/链接 boost::regex 库?

c++ - 使用 Boost 的正则表达式标记化仅获取单词的最后一个字母

c++ - 来自变量的 QJsonObject 部分路径

c++ - 将特征数组转换为特征向量

c++ - 从给定的 Boost token_iterator 识别原始字符串中的位置

c++ - boost::asio,为什么我的套接字在调用 async_receive_from 后立即运行回调函数?

c++ - 使用 ifstream 读取 float

c++ - 是否有 BOOST 池固定大小的分配器?

Boost_LIBRARIES 未定义