【问题标题】:std::bad_variant_access error when trying to store value to std::variant in map尝试将值存储到映射中的 std::variant 时出现 std::bad_variant_access 错误
【发布时间】:2020-06-29 16:37:06
【问题描述】:

我正在使用 std::variant 将文件解析为映射(以支持两种类型的值),但我无法找到将值存储到映射中的正确方法。

我得到一个: std::bad_variant_access

what(): 意外索引

这是地图定义:

typedef struct op{
   std::string name;
   map<std::string, std::variant<uint16_t,float> > params;
}operation;

这是解析函数:

int test(std::string file_name)
{
   ifstream inFile;

   inFile.open(file_name);
   if (!inFile) {
      std::cout << "Unable to open file: " << input_file_name << endl;
      return(-1); 
   }      

   std::string key;
   std::string value;
   operation op;

   /* read op. name. */
   getline(inFile, key, ':') && getline(inFile, value);
   assert(key.compare("op_name") == 0);
   op.name = remove_leading_spaces(value);
 
   getline(inFile, value);
   stringstream s_(value);
   std::string key_;
   while(getline(s_, key_, ':') && getline(s_, value, ',')){ 
        key = remove_leading_spaces(key_);
        if (key.compare("factor") == 0){
            std::get<float>(op.params[key]) = std::stof(value);
        }
        else{
            std::get<uint16_t>(op.params[key]) = std::stoi(value);
        }
   }
.
.
.
// rest of the function is irrelevant 
.
.

uint16_t解析没有问题。

我尝试更改变体的顺序,使其成为 std::variant,然后在 else 中失败。 所以我知道我访问变体的方式是错误的(或者可能是因为地图没有初始化?)但我不知道如何修复它。

我应该使用 std::visit 而不是 std::get 吗?如果有,怎么做?

我们将不胜感激。

谢谢。

【问题讨论】:

    标签: c++ c++17 stdmap std-variant


    【解决方案1】:

    您正在寻找std::variant::emplace()。在你的代码中:

    if (key.compare("factor") == 0){
      op.params[key].emplace<float>(std::stof(value));
    } else {
      op.params[key].emplace<uint16>(std::stoi(value));
    }
    

    但我不知道uint16 是什么——你真的在使用uint16_t吗?

    【讨论】:

      猜你喜欢
      • 2020-07-28
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多