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

允我心安 提交于 2020-04-10 12:49:37

问题


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]

This is the code

#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?


回答1:


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.


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




回答2:


Since nobody is showing how to use C++ 11 with g++, it looks like this...

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

Hopefully this saves Google visitors an extra search.




回答3:


This is because you are using for (int x: temps) which is a c++11 construct. Try the following if you are using eclipse:

  • Right-click on the the project and select "Properties"

  • Navigate to C/C++ Build -> Settings

  • Select the Tool Settings tab.

  • Navigate to GCC C++ Compiler -> Miscellaneous

  • In the option setting labeled Other Flags add -std=c++11

Now rebuild your project.

Update: For Atom follow below steps:

Go to ~/.atom/packages/script/lib/grammers.coffee

Go to the C++ section (ctrl-f c++):

Then change this line:

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

to this:

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

i.e. add -std=c++11 -stdlib=libc++ and remove -Wc++11-extensions

Hope this helps!



来源:https://stackoverflow.com/questions/49269691/why-am-i-getting-a-warning-for-this-range-based-for-loop-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!