Efr*_*lez 5 c++ warnings for-loop compiler-warnings c++11
我目前正在使用Bjarne Stroustrup的书(第2版)自学C++.在其中一个示例中,他使用for-for-loop来读取向量中的元素.当我为自己编写和编译代码时,我得到了这个警告.当我运行代码时,它似乎正在工作并计算平均值.为什么我收到这个警告,我应该忽略它吗?另外,为什么范围 - 在示例中使用int而不是double,但仍返回double?
temp_vector.cpp:17:13: warning: range-based for loop is a C++11
extension [-Wc++11-extensions]
Run Code Online (Sandbox Code Playgroud)
这是代码
#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;
}
Run Code Online (Sandbox Code Playgroud)
在类似的说明中:我应该如何根据循环标准来查看范围?
yan*_*000 11
由于没有人展示如何将 C++ 11 与 g++ 一起使用,它看起来像这样......
g++ -std=c++11 your_file.cpp -o your_program
Run Code Online (Sandbox Code Playgroud)
希望这可以为 Google 访问者节省额外的搜索。
小智 9
对于在 VS Code 上使用代码运行器扩展的用户,请转到代码运行器扩展设置。查找 -> 代码运行器:执行器映射。单击编辑settings.json并找到终端的 cpp 脚本并按如下方式设置:
"cpp": "cd $dir && g++ -std=c++11 $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt"
Run Code Online (Sandbox Code Playgroud)
传递-std=c++11给编译器; 你的(古代)编译器默认为C++ 03,并警告你它接受一些较新的C++结构作为扩展.
远程基础扩展为基于迭代器的for循环,但错别字的机会较少.