C++ 如何在C++中使用每个循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17267216/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 21:03:47  来源:igfitidea点击:

How to use for each loop in c++

c++

提问by Ra1nWarden

#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;
}

This c++ code does not compile. Error msg: main.cpp:21: error: a function-definition is not allowed here before ':' token Question: Is there a for each loop in c++ (range for loop?)? what is wrong with the for each loop above?

此 C++ 代码无法编译。错误消息:main.cpp:21:错误:在':'标记之前不允许有函数定义 问题:C++ 中是否有 for each 循环(循环范围?)?上面的 for each 循环有什么问题?

Thanks in advance.

提前致谢。

回答by Potatoswatter

The code is valid, as can be demonstrated on an online compiler.

代码是有效的,可以在在线编译器上进行演示。

Please refer to your compiler documentation to be sure you have enabled C++11. The option is often called -std=c++11. You might have to download an upgrade; check your package manager for GCC (currently at 4.8) or Clang (currently 3.3).

请参阅您的编译器文档以确保您已启用 C++11。该选项通常称为-std=c++11。您可能需要下载升级;检查 GCC(当前为 4.8)或 Clang(当前为 3.3)的包管理器。

回答by Hut8

Prior to C++11x, for_eachis defined in the algorithmheader. Simply use:

在 C++11x 之前,for_eachalgorithm头文件中定义。只需使用:

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

where fnis a function to which the element will be passed, and the first two arguments are input iterators.

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

Also, after including both stringand algorithmyou could just use

此外,在包括两者之后stringalgorithm您就可以使用

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

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