#include<iostream>#include<iterator> // std::sizeintmain(){constexprintscores[]{84,92,76,81,56};constexprintnumStudents{std::size(scores)};intmaxScore{0};// keep track of our largest scorefor(intstudent{0};student<numStudents;++student){if(scores[student]>maxScore){maxScore=scores[student];}}std::cout<<"The best score was "<<maxScore<<'\n';return0;}
尽管使用 for 循环可以很方便的遍历一个数组,但是在真正使用的时候,这种方式容易出错,而且也容易犯差一错误。
#include<iostream>intmain(){constexprintfibonacci[]{0,1,1,2,3,5,8,13,21,34,55,89};for(intnumber:fibonacci)// iterate over array fibonacci{std::cout<<number<<' ';// we access the array element for this iteration through variable number}std::cout<<'\n';return0;}
程序的输出结果为:
1
0 1 1 2 3 5 8 13 21 34 55 89
让我们仔细研究一下上面代码是如何工作的。首先,执行 for 循环,变量number 的值首先被设置为数组中的第一个元素,也就是 0。程序随后打印该值,即打印0.然后,for 循环再次执行,number被设置为数组的第二个元素,即1。然后打印1。for 循环不断地执行,依次打印出数组中的每个元素,直到遍历完全部数组。然后,循环截止了,程序继续执行(返回0给操作系统)。
#include<iostream>intmain(){constexprintfibonacci[]{0,1,1,2,3,5,8,13,21,34,55,89};for(autonumber:fibonacci)// type is auto, so number has its type deduced from the fibonacci array{std::cout<<number<<' ';}std::cout<<'\n';return0;}
For-each 循环和引用
在下面的例子中,element被声明为一个值变量:
12345
std::stringarray[]{"peter","likes","frozen","yogurt"};for(autoelement:array)// element will be a copy of the current array element{std::cout<<element<<' ';}
std::stringarray[]{"peter","likes","frozen","yogurt"};for(auto&element:array)// The ampersand makes element a reference to the actual array element, preventing a copy from being made{std::cout<<element<<' ';}
std::stringarray[]{"peter","likes","frozen","yogurt"};for(constauto&element:array)// element is a const reference to the currently iterated array element{std::cout<<element<<' ';}
#include<iostream>intmain(){constexprintscores[]{84,92,76,81,56};intmaxScore{0};// keep track of our largest scorefor(autoscore:scores)// iterate over array scores, assigning each value in turn to variable score{if(score>maxScore){maxScore=score;}}std::cout<<"The best score was "<<maxScore<<'\n';return0;}
#include<iostream>#include<vector>intmain(){std::vectorfibonacci{0,1,1,2,3,5,8,13,21,34,55,89};// note use of std::vector here rather than a fixed array// Before C++17// std::vector<int> fibonacci{ 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 };for(autonumber:fibonacci){std::cout<<number<<' ';}std::cout<<'\n';return0;}
#include<iostream>intsumArray(constintarray[])// array is a pointer{intsum{0};for(autonumber:array)// compile error, the size of array isn't known{sum+=number;}returnsum;}intmain(){constexprintarray[]{9,7,5,3,1};std::cout<<sumArray(array)<<'\n';// array decays into a pointer herereturn0;}
#include<iostream>intmain(){std::stringnames[]{"Alex","Betty","Caroline","Dave","Emily"};// Names of the studentsconstexprintscores[]{84,92,76,81,56};intmaxScore{0};for(inti{0};autoscore:scores)// i is the index of the current element{if(score>maxScore){std::cout<<names[i]<<" beat the previous best score of "<<maxScore<<" by "<<(score-maxScore)<<" points!\n";maxScore=score;}++i;}std::cout<<"The best score was "<<maxScore<<'\n';return0;}
输出结果:
123
Alex beat the previous best score of 0 by 84 points!
Betty beat the previous best score of 84 by 8 points!
The best score was 92
这里的 int i{ 0 }; 是 init-statement,它会在循环执行时执行一次。在每次循环时,i就被递增1,类似与普通的循环。不过,如果我们在循环中使用continue的话,++i会被跳过,导致非预期的结果。如果你需要使用 continue 的话,请确保i的递增在continue之前进行。