为什么在C ++中针对基于范围的for循环收到警告? [英] Why am I getting a warning for this range-based for loop in C++?

查看:336
本文介绍了为什么在C ++中针对基于范围的for循环收到警告?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am currently self-teaching myself C++ using Bjarne Stroustrup's book (2nd ed). In one of the examples, he uses a range-for-loop to read the elements in a vector. When I wrote and compiled the code for myself I get this warning. When I run the code, it seems to be working and calculates the mean. Why am I receiving this warning and should I ignore it? Also, why is the range-for using int instead of double in the example, but still returns a 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;
}

类似地,我应该如何看待范围

On a similar note: how should I view the range-for in terms of a standard for loop?

推荐答案

通过-std = c ++ 11 编译器;您的(古老的)编译器默认使用C ++ 03,并警告您它正在​​接受某些较新的C ++结构作为扩展。

Pass --std=c++11 to the compiler; your (ancient) compiler is defaulting to C++03 and warning you that it is accepting some newer C++ constructs as extensions.

Range的范围已扩展放入基于迭代器的for循环中,但出现错别字的机会更少。

Ranged base for is expanded into an iterator-based for loop, but with less opportunities for typos.

这篇关于为什么在C ++中针对基于范围的for循环收到警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆