auto auto 与for结合 begin(),end()说明
auto
c++11标准引入auto类型说明符 必须有初始值 通过初始值来推断变量的类型
# include <cstdio>
using namespace std;
int main ( ) { int v1 = 10 ; auto v2 = v1; printf ( "v2=%d\n" , v2) ; double v3= 10.5 ; auto v4 = v3; printf ( "v4=%f\n" , v4) ; return 0 ;
}
与for结合
c++11标准引入简单for语句,遍历容器或序列的所有元素 语法for(declaration: expression) 遍历数组实例
# include <iostream>
using namespace std;
int main ( ) { int num[ 10 ] = { 1 , 2 , 3 } ; for ( auto v: num) cout<< v<< " " ; cout<< endl; return 0 ;
}
# include <iostream>
using namespace std;
int main ( ) { int num[ 10 ] = { 1 , 2 , 3 } ; for ( auto & v: num) v= v* 2 ; for ( auto & v: num) cout<< v<< " " ; cout<< endl; return 0 ;
} ```
* vector中```cpp
vector< int > num = { 1 , 2 , 3 } ;
for ( auto & v: num) v= v* 2 ;
string s= "abc" ;
for ( auto & v: s) v= v+ 1 ;
begin(),end()说明
v与vector中的元素绑定,修改v的值即改变其所绑定的值。
for ( auto & v: num) v= v* 2 ;
for ( auto it= num. begin ( ) ; it!= num. end ( ) ; ++ it) auto & v= * it; v= v* 2 ;