Why am I getting a warning for this range-based fo

2020-07-09 08:41发布

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?

3条回答
劳资没心,怎么记你
2楼-- · 2020-07-09 08:50

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楼-- · 2020-07-09 08:55

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!

查看更多
SAY GOODBYE
4楼-- · 2020-07-09 09:03

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.

查看更多
登录 后发表回答