如何在 c++ 中为每个循环使用
How to use for each loop in c++
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
int main() {
string str("hello world!");
for (auto &c : str)
c = toupper(c);
cout << str;
return 0;
}
此 c++ 代码无法编译。错误消息: main.cpp:21:错误:此处不允许在":"标记之前使用函数定义问题:在 c++ 中是否有一个 for 每个循环(循环的范围?上面的每个循环有什么问题?
提前谢谢。
代码是有效的,可以在在线编译器上演示。
请参阅编译器文档以确保已启用 C++11。该选项通常称为 -std=c++11
。您可能需要下载升级;检查您的软件包管理器中的 GCC(当前为 4.8(或 Clang(当前为 3.3(。
在 C++11x 之前,for_each
在 algorithm
标头中定义。只需使用:
for_each (vec.begin(), vec.end(), fn);
其中fn
是元素将传递到的函数,前两个参数是输入迭代器。
此外,在包含string
和algorithm
之后,您可以使用
std::transform(str.begin(), str.end(),str.begin(), ::toupper);
相关文章:
- 如何循环打印顶点结构
- 如何在C++中从两个单独的for循环中添加两个数组
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 正在尝试了解输入验证循环
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- 循环后如何继续阅读
- Ardunio UNO解决了多个重叠的定时器循环
- Eigen如何在容器循环中干净地附加矩阵
- 在某些循环内使用vector.push_back时出现分段错误
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 为什么我的for循环不能正确获取argv
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- while循环中while循环的时间复杂度是多少
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 为什么在这个代码结束循环中没有得到结束
- 在基于范围的for循环中使用结构化绑定声明
- 用于C++中带有数组和指针的循环
- 循环中的随机函数
- 是什么阻止DOMTimerCoordinator::NextID进入无休止的循环
- 在循环C++中指定字符串之后,不会打印该字符串