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?
Since nobody is showing how to use C++ 11 with g++, it looks like this...
Hopefully this saves Google visitors an extra search.
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:
to this:
i.e. add
-std=c++11 -stdlib=libc++
and remove-Wc++11-extensions
Hope this helps!
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.