简体   繁体   English

将一对值与字符串进行比较

[英]compare a value of a pair with a string

config is a map within a map: config是一个映射内的一个映射:

   std::map<std::string, std::map<std::string, std::string>> config;

I'm trying to parse a configuration file (.ini). 我正在尝试解析配置文件(.ini)。

so, 所以,

config[sectionName] = map<std::string, std::string>>();
config[sectionName][optionKey] = value; //when option and value store a string.

Now, 现在,

I'm trying to implement this function. 我正在尝试实现此功能。 I get errors: one is that "sections == section" and " sections.second == "false" " can't be compared. 我得到了错误:一种是无法比较“ sections == section”和“ sections.second ==“ false””。 The error I receive is "error: invalid operands to binary expression". 我收到的错误是“错误:对二进制表达式无效的操作数”。

Could anyone please explain me what is wrong? 谁能解释我怎么了?

/*
 * Searches for option's value in section and converts it to a bool if possible.
 *
 * If the value isn't one of the options below or if section/option
 * don't exist the conversion fails.
 *
 * Returns a pair of <bool, bool>
 *  first is set to true if conversion succeeded, false otherwise.
 *  If the conversion succeeds, second is the converted boolean value.
 *  If the conversion fails, it doesn't matter what second is set to.
 *
 *  Converts to true: "true", "yes", "on", "1"
 *  Converts to false: "false", "no", "off", "0"
 *
 */
pair<bool, bool> ConfigParser::getBool(const string& section,
    const string& option) const
{
  for(const auto& sections : config){
    if(sections == section && sections.first != ""){

      if(sections.second == "true" || sections.second == "yes" ||
          sections.second == "on" || sections.second == "1"){

        return pair<bool, bool>(true, true);
      }
      if(sections.second == "false" || sections.second == "no" ||
          sections.second == "off" || sections.second == "0"){

        return pair<bool, bool>(true, false);
      }
    }
  }
  return pair<bool, bool>(false, false);
}

Consider your code fragment: 考虑一下您的代码片段:

for(const auto& sections : config) {
     if(sections == section && sections.first != "") {

Here sections is a pair<string, map<string, string>> , and section is a string . 在这里, sectionspair<string, map<string, string>> ,而sectionstring

Those aren't comparable. 这些没有可比性。

If you just want to look up a section section , there are much easier ways. 如果您只想查找section ,则有很多简单的方法。 for example: 例如:

pair<bool, bool> ConfigParser::getBool(const string& section,
                                       const string& option) const
{
    auto it = config.find(section);
    if (it == config.end()) { return {false, false}; }

    auto jt = it->second.find(option);
    if (jt == it->second->end()) { return {false, false}; }

    // parse jt->second
    return {true, /* parse result */ };
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM