我见过使用矢量的代码,
vector<int>s;
s.push_back(11);
s.push_back(22);
s.push_back(33);
s.push_back(55);
for (vector<int>::iterator it = s.begin(); it!=s.end(); it++) {
cout << *it << endl;
}
Run Code Online (Sandbox Code Playgroud)
它是一样的
for (auto it = s.begin(); it != s.end(); it++) {
cout << *it << endl;
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下使用auto关键字有多安全?如果矢量类型是float
什么?string
?
Unc*_*ens 46
该自动关键字简单地要求编译器来推断从初始化变量的类型.
即使是前C++ 0x编译器也知道(初始化)表达式的类型,并且通常可以在错误消息中看到该类型.
#include <vector>
#include <iostream>
using namespace std;
int main()
{
vector<int>s;
s.push_back(11);
s.push_back(22);
s.push_back(33);
s.push_back(55);
for (int it=s.begin();it!=s.end();it++){
cout<<*it<<endl;
}
}
Line 12: error: cannot convert '__gnu_debug::_Safe_iterator<__gnu_cxx::__normal_iterator<int*, __gnu_norm::vector<int, std::allocator<int> > >, __gnu_debug_def::vector<int, std::allocator<int> > >' to 'int' in initialization
Run Code Online (Sandbox Code Playgroud)
该自动关键字就是允许你利用这方面的知识优势-如果你(编译器)知道正确的类型,只是选择了我!
use*_*567 40
这是附加信息,而不是答案.但由于我没有声名誉,我只能写在这里:
在C++ 11中,您可以编写:
for (auto& it : s) {
cout << it << endl;
}
Run Code Online (Sandbox Code Playgroud)
代替
Run Code Online (Sandbox Code Playgroud)for (auto it = s.begin(); it != s.end(); it++) { cout << *it << endl; }
它具有相同的含义.
更新:请参阅@ Alnitak的评论.
Kar*_*nek 13
auto关键字从=右侧的表达式中获取类型.因此它可以用于任何类型,唯一的要求是在声明它时初始化auto变量,以便编译器可以推断出类型.
例子:
auto a = 0.0f; // a is float
auto b = std::vector<int>(); // b is std::vector<int>()
MyType foo() { return MyType(); }
auto c = foo(); // c is MyType
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
127816 次 |
最近记录: |