如何在 c++ 中为每个循环使用

How to use for each loop in c++

本文关键字:循环 c++      更新时间:2023-10-16
#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_eachalgorithm 标头中定义。只需使用:

for_each (vec.begin(), vec.end(), fn);

其中fn是元素将传递到的函数,前两个参数是输入迭代器。

此外,在包含stringalgorithm之后,您可以使用

std::transform(str.begin(), str.end(),str.begin(), ::toupper);