error: std::string was not declared in this scope, in for loop C++

error: std::string was not declared in this scope, in for loop C++

我试图为 class 实现使用 GMP 库的代码,但未能找出此问题的根源。我之前在 unordered_map 上有 运行 类似的代码,所以这个错误让我很困惑。据我所知, std::string 应该通过调用 for 循环在范围内声明。会不会跟使用GMP库有关?

int main(int argc, char** argv){
std::map<mpz_class, std::string> number_names;
std::ifstream names_file("/srv/datasets/number_names.txt");
if(!names_file.is_open()){
  std::cout << "error reading /srv/datasets/number_names.txt\n";
  return -1;
}
mpz_class num;
for (std::string name : names_file >> name >> num){ // line throwing error
  number_names[num] = name;
}
auto value = mpz_class(argv[1]);
std::vector<std::string> output = some_func(value, number_names);

}

完整的错误消息如下:

    as10.cpp:75:43: error: ‘name’ was not declared in this scope 
    75 |     for (std::string name : names_file >> name >> num)
for (std::string name : names_file >> name >> num){
  number_names[num] = name;
}

这不是基于范围的 for 循环在 C++ 中的工作方式,因此这是一个语法错误。看样子你打错了。

也许你想要的是:

std::string name;
while(names_file >> name >> num){
    number_names[num] = name;
}

或者:

for (std::string name; names_file >> name >> num;){
    number_names[num] = name;
}