range-for 是对一定范围内的(如容器vector或者一段string)的循环遍历语句,从头到尾。参考Range-based for loop (since C++11) - cppreference.com<
Executes a for loop over a range.
Used as a more readable equivalent to the traditional for loop operating over a range of values, such as all elements in a container.
>
我们需要声明一个变量,叫做range-declaration(如下文中的变量c), 并且需要为其确定一个类型,通常我们用auto这个关键字 ,进行自动类型推导。
此时就涉及到标题中auto,auto&, auto&&, const auto&的使用,其实更多的是C++中值传递,引用传递,右值引用等知识,使用以下代码进行了测试,以及测试结果。
#include#include #include #include #include using std::vector; int main() { //just auto c, 创建拷贝,每次遍历都是copy一次,不会对str中的元素进行修改 std::string str("str ing1"); std::cout< 学习时用的参考链接:
C++ 遍历循环表达示 auto, auto&, auto&&
C++ 中的auto、auto&、auto&&、const auto&_橙橙小狸猫的博客-CSDN博客_auto&&
Range-based for loop (since C++11) - cppreference.com



