在C++ STL中使用auto关键字

dat*_*ili 37 c++ stl c++11

我见过使用矢量的代码,

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)

代替

for (auto it = s.begin(); it != s.end(); it++) {
    cout << *it << endl;
}
Run Code Online (Sandbox Code Playgroud)

它具有相同的含义.

更新:请参阅@ Alnitak的评论.

  • 那些不等价 - 在第一个变量`it`是`value_type`类型并且实际上不是迭代器. (16认同)

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)

  • 虽然技术上是正确的.我希望这成为不好的做法.如果每个人都宣称他们所有的变量都是"自动",那么人类就很难阅读和理解(我们会走上无类型语言的道路).对于我们实际上并不关心类型的情况,应该保留auto的使用,只要它在我们想要的庄园中行为(例如迭代器,我们实际上并不关心我们得到的迭代器,只要我们可以像迭代器一样使用它. (12认同)