首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用std::string键从boost::unordered::unordered_map恢复值时出错

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

Stack Overflow用户
提问于 2013-02-21 19:21:12
回答 1查看 282关注 0票数 0

我将正则表达式匹配得到的结果存储在unordered_map中。cout sub匹配m1.str(),m2.str()正确显示密钥-值对。

虽然当我将它们存储在unordered_map中时,我总是得到一个异常,报告关键字不是found.This,但代码是:

代码语言:javascript
复制
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是配置文件中“变量”的名称。cout << m1.str()完美地显示了它,但在unordered_map中找不到。有什么想法吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-02-21 19:28:46

最有可能的情况是,您放在无序映射中的键包含空白(在输出时看不到),因此以后找不到它。

在您的正则表达式^(.+)\\s*=\\s*(.+)中,第一个(.+)将贪婪地匹配尽可能多的字符,包括前导和尾随空格。它后面的\\s*始终匹配空字符串。为了防止出现这种情况,您可以只对非空格使用(\\S+),或者使用非贪婪的(.+?)

顺便说一句,while (!fs.eof())错了。请改用while (std::getline(fs, line)) {...}

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15000959

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档