我试着理解如何auto在C++中使用.对我来说,理解某事的最好方法是看一个例子.但是,我看到的例子并不那么简单.例如,这里是" C++ 0x auto keyword的含义,例如? ".要理解这个例子,我需要知道什么是"模板","指针","malloc"等等.
任何人都可以使用auto给出一个简约的例子,这样可以很容易地理解它的用途吗?
小智 13
int a = 10;
int b = 20;
auto c = a+b; // c will be int
Run Code Online (Sandbox Code Playgroud)
Zde*_*vic 12
auto 用于类型推断,即基于表达式声明类型,而不是显式声明它.
auto val = 3; // here, val is declared as an integer
Run Code Online (Sandbox Code Playgroud)
显然这不是一个很大的优势,int val = 3所以让我们做一个更好的例子:
std::vector<int> container; // ...
for (auto it = container.begin(); it != container.end(); it++) {
// type of it is std::vector<int>::iterator, but you don't need to state that
}
Run Code Online (Sandbox Code Playgroud)
在这里你不必关心真正的容器类型,即std::vector<int>::iterator it = c.begin().此外,您可以container从矢量更改为列表,并且循环仍然可以在没有任何更改的情况下工作,it因为可以正确推导出类型.
注意:在C++ 11中,您可以将上面的循环编写为,for( auto it: container)但这可以更好地作为说明.