为什么我在C++中收到有关此基于范围的 for 循环的警告

Why am I getting a warning for this range-based for loop in C++?

本文关键字:于范围 范围 循环 for 警告 C++ 为什么      更新时间:2023-10-16

我目前正在自学C++使用Bjarne Stroustrup的书(第2版(。在其中一个示例中,他使用范围循环来读取向量中的元素。当我为自己编写和编译代码时,我收到此警告。当我运行代码时,它似乎正在工作并计算平均值。为什么我会收到此警告,我应该忽略它吗?另外,为什么 range-for 在示例中使用 int 而不是 double,但仍然返回 double?

temp_vector.cpp:17:13: warning: range-based for loop is a C++11 
extension [-Wc++11-extensions]

这是代码

#include<iostream>
#include<vector>
using namespace std;
int main ()
{
  vector<double> temps;     //initialize a vector of type double
  /*this for loop initializes a double type vairable and will read all 
    doubles until a non-numerical input is detected (cin>>temp)==false */
  for(double temp; cin >> temp;)
    temps.push_back(temp);
  //compute sum of all objects in vector temps
  double sum = 0;
 //range-for-loop: for all ints in vector temps. 
  for(int x : temps)     
    sum += x;
  //compute and print the mean of the elements in the vector
      cout << "Mean temperature: " << sum / temps.size() << endl;
  return 0;
}

同样,我应该如何根据标准 for 循环查看范围?

由于没有人展示如何将 C++ 11 与 g++ 一起使用,因此看起来像这样......

g++ -std=c++11 your_file.cpp -o your_program

希望这能为谷歌访问者节省额外的搜索。

--std=c++11传递给编译器;您的(古代(编译器默认为 C++03,并警告您它正在接受一些较新的C++构造作为扩展。

<小时 />

范围基础 for 扩展为基于迭代器的 for 循环,但拼写错误的机会更少。

对于在 VS 代码上使用代码运行程序扩展的用户,请转到代码运行程序扩展设置。find -> 代码运行器:执行器映射。单击settings.json中的编辑并找到终端的 cpp 脚本并按如下方式设置:

"cpp": "cd $dir && g++  -std=c++11 $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt"

这是因为您使用的是 for (int x: temps) c ++ 11 构造。如果您使用的是 eclipse,请尝试以下操作:

  • 右键单击项目并选择"属性">

  • 导航到 C/C++ 生成 -> 设置

  • 选择"工具设置"选项卡。

  • 导航到 GCC C++编译器 -> 杂项

  • 在标记为"其他标志"的选项设置中添加 -std=c++11

现在重新生成项目。

更新:对于Atom,请按照以下步骤操作:

转到 ~/.atom/packages/script/lib/grammers.coffee

转到C++部分 (ctrl-f c++(:

然后更改此行:

args: (context) -> ['-c', "xcrun clang++ -fcolor-diagnostics -Wc++11-extensions // other stuff

对此:

args: (context) -> ['-c', "xcrun clang++ -fcolor-diagnostics -std=c++11 -stdlib=libc++ // other stuff

即添加-std=c++11 -stdlib=libc++并删除-Wc++11-extensions

希望这有帮助!