为什么我会收到 C 中这个基于范围的 for 循环的警告?

新手上路,请多包涵

我目前正在使用 Bjarne Stroustrup 的书(第 2 版)自学 C++。在其中一个示例中,他使用 range-for-loop 来读取向量中的元素。当我为自己编写和编译代码时,我收到了这个警告。当我运行代码时,它似乎正在工作并计算平均值。为什么我会收到此警告,我应该忽略它吗?另外,为什么示例中的 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 循环查看范围?

原文由 Efraín González 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 600
1 个回答

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

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

希望这可以为 Google 访问者节省额外的搜索。

原文由 yanksrock1000 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题