What does quot; for (const auto amp;s : strs) {} quot; mean?(是什么意思?for (const auto amp;s : strs) {} quot;意思是?)
问题描述
What does for (const auto &s : strs) mean? What is the function of colon :? 
vector<string> &strs;
for (const auto &s : strs){
   //
}
It's actually a C++11 feature called "range-based for-loops".
In this case, it's basically an easier-to-write replacement for:
// Let's assume this vector is not empty.
vector<string> strs;
const vector<string>::iterator end_it = strs.end();
for (vector<string>::iterator it = strs.begin(); it != end_it; ++it) {
  const string& s = *it;
  // Some code here...
}
The : is part of the new syntax.
On the left you basically have a variable declaration that will be bound to the elements of the vector and one the right you have the variable to iterate on (also called "range expression").
Here is an excerpt of the linked documentation that explains the prerequisites for the range-expressions:
range_expression is evaluated to determine the sequence or range to iterate. Each element of the sequence, in turn, is dereferenced and assigned to the variable with the type and name given in range_declaration.
begin_expr and end_expr are defined as follows:
If __range is an array, then begin_expr is __range and end_expr is (__range + __bound), where __bound is the number of elements in the array (if the array has unknown size or is of an incomplete type, the program is ill-formed)
If __range's type is a class type with either or both a begin or an end member function, then begin_expr is __range.begin() and end_expr is __range.end();
Otherwise, begin_expr is begin(__range) and end_expr is end(__range), which are found via argument-dependent lookup with std as an associated namespace.
Note that thanks to all this, range-based for loops also support iterating over C arrays as std::begin/std::end works with those too.
这篇关于是什么意思?for (const auto &s : strs) {} "意思是?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:是什么意思?for (const auto &s : strs) {} "意思是?
				
        
 
            
        基础教程推荐
- C++结构和函数声明。为什么它不能编译? 2022-11-07
 - 如何检查GTK+3.0中的小部件类型? 2022-11-30
 - 如何在 C++ 中初始化静态常量成员? 2022-01-01
 - 在 C++ 中计算滚动/移动平均值 2021-01-01
 - 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
 - 如何通过C程序打开命令提示符Cmd 2022-12-09
 - 我有静态或动态 boost 库吗? 2021-01-01
 - 常量变量在标题中不起作用 2021-01-01
 - 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
 - 这个宏可以转换成函数吗? 2022-01-01
 
    	
    	
    	
    	
    	
    	
    	
    	
						
						
						
						
						
				
				
				
				