std::bad_variant_access 尝试将值存储到地图中的 std::variant 时出错
std::bad_variant_access error when trying to store value to std::variant in map
我正在使用 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 吗?如果可以,怎么做?
任何帮助将不胜感激。
谢谢。
您正在寻找 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
吗?
我正在使用 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
我应该使用 std::visit 而不是 std::get 吗?如果可以,怎么做?
任何帮助将不胜感激。
谢谢。
您正在寻找 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
吗?