为什么我在C++中收到有关此基于范围的 for 循环的警告
Why am I getting a warning for this range-based for loop in C++?
我目前正在自学C++使用Bjarne Stroustrup的书(第2版(。在其中一个示例中,他使用范围循环来读取向量中的元素。当我为自己编写和编译代码时,我收到此警告。当我运行代码时,它似乎正在工作并计算平均值。为什么我会收到此警告,我应该忽略它吗?另外,为什么 range-for 在示例中使用 int 而不是 double,但仍然返回 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;
}
同样,我应该如何根据标准 for 循环查看范围?
由于没有人展示如何将 C++ 11 与 g++ 一起使用,因此看起来像这样......
g++ -std=c++11 your_file.cpp -o your_program
希望这能为谷歌访问者节省额外的搜索。
将--std=c++11
传递给编译器;您的(古代(编译器默认为 C++03,并警告您它正在接受一些较新的C++构造作为扩展。
范围基础 for 扩展为基于迭代器的 for 循环,但拼写错误的机会更少。
对于在 VS 代码上使用代码运行程序扩展的用户,请转到代码运行程序扩展设置。find -> 代码运行器:执行器映射。单击settings.json
中的编辑并找到终端的 cpp 脚本并按如下方式设置:
"cpp": "cd $dir && g++ -std=c++11 $fileName -o $fileNameWithoutExt && $dir$fileNameWithoutExt"
这是因为您使用的是 for (int x: temps)
c ++ 11 构造。如果您使用的是 eclipse,请尝试以下操作:
-
右键单击项目并选择"属性">
-
导航到 C/C++ 生成 -> 设置
-
选择"工具设置"选项卡。
-
导航到 GCC C++编译器 -> 杂项
-
在标记为"其他标志"的选项设置中添加 -std=c++11
现在重新生成项目。
更新:对于Atom,请按照以下步骤操作:
转到 ~/.atom/packages/script/lib/grammers.coffee
转到C++部分 (ctrl-f c++(:
然后更改此行:
args: (context) -> ['-c', "xcrun clang++ -fcolor-diagnostics -Wc++11-extensions // other stuff
对此:
args: (context) -> ['-c', "xcrun clang++ -fcolor-diagnostics -std=c++11 -stdlib=libc++ // other stuff
即添加-std=c++11 -stdlib=libc++
并删除-Wc++11-extensions
希望这有帮助!
- 为什么我的变量存在于其范围之外
- set_intersection范围范围
- 满足标准::范围::范围概念
- 向量向量的范围范围
- C++参数类型以接受适用于基于范围的 for 循环的所有序列
- 代码具有特定于函数的变量,用于更改范围之外的值
- 将自适应阈值应用于范围函数 opencv c++
- 用辅助方法范围范围的问题来操纵字符串
- C++:将参数应用于函数范围
- C++11:用容器参数定义函数(类似于基于范围的)
- 在C /STL中,是否有相当于Python范围()的紧凑型
- 用于循环范围范围
- 如何制作增强多指数复合范围语句,等效于x和y
- std::copy_n 是否适用于重叠范围?
- 依赖于模板参数的范围查找
- 标准算法 any_of()、all_of() 和 none_of() 应用于空范围
- 常数,但仅适用于此范围的剩余部分
- 确定谓词是否适用于一个范围的全部、部分或全部元素
- 延长临时的生命周期,适用于块范围的聚合,但不是通过"新";为什么?
- 矢量超出范围/范围检查