今天意外之中发现了c++中for循环的另类用法,一般来说for循环的用法是这样的:
for ( initialization ; condition ; increase ) statement;
- 执行初始化变量initialization;
- 检查判断条件condition;
- 执行语句statement;
- 执行increase。
可c++有另一种基于范围的for循环,语句如下:
for ( declaration : range ) statement;
- 在冒号“:”前声明变量declaration;
- 在冒号“:”后为范围range;
- 运行语句statement。
这种循环正如c++官方文档中所说一样:
This loop is automatic and does not require the explicit declaration of any counter variable.
这个循环是自动的,不需要任何计数器变量的显式声明。
用一个例子来理解一下这种循环:
*在这个循环中,定义了一个char类型的变量c,在string类型的str字符串范围内,按字符遍历并输出。
基于范围的循环中,声明变量时,常常会使用类型auto来自动推导变量类型,我们可以将代码替换成:
*在这里, 类型c
被自动推导出为str
中元素的类型。
例题:
LeetCode2114. 句子中的最多单词数(点击链接读题,不在此赘述 :-D)
对于未知长度的sentences,一般的for循环很难确立计数器的显式声明,但是使用简单迭代for循环,可以很好的解决这个问题。
int mostWordsFound(vector<string>& sentences) {
int res=0;
//简单迭代循环
for(string sentence:sentences){
int cnt=count(sentence.begin(),sentence.end(),' ')+1;
res=max(res,cnt);
}
return res;
}