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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3434256/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 12:50:20  来源:igfitidea点击:

Use the auto keyword in C++ STL

c++stlc++11

提问by dato datuashvili

I have seen code which use vector,

我见过使用向量的代码,

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;
}

It is same as

它与

for (auto it = s.begin(); it != s.end(); it++) {
    cout << *it << endl;
}

How safe is in this case the use of the auto keyword? And what about if type of vector is float? string?

在这种情况下使用 auto 关键字有多安全?如果向量的类型是float呢?string?

回答by UncleBens

The autokeyword is simply asking the compiler to deduce the type of the variable from the initialization.

自动关键字简单地要求编译器来推断从初始化变量的类型。

Even a pre-C++0x compiler knows what the type of an (initialization) expression is, and more often than not, you can see that type in error messages.

即使是 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

The autokeyword simply allows you to take advantage of this knowledge - if you (compiler) know the right type, just choose for me!

自动关键字就是允许你利用这方面的知识优势-如果你(编译器)知道正确的类型,只是选择了我!

回答by user1234567

It's additional information, and isn't an answer.

这是附加信息,而不是答案。

In C++11 you can write:

在 C++11 中,你可以这样写:

for (auto& it : s) {
    cout << it << endl;
}

instead of

代替

for (auto it = s.begin(); it != s.end(); it++) {
    cout << *it << endl;
}
for (auto it = s.begin(); it != s.end(); it++) {
    cout << *it << endl;
}

It has the same meaning.

它具有相同的含义。

Update: See the @Alnitak's comment also.

更新另请参阅@Alnitak 的评论。

回答by Karel Petranek

The auto keyword gets the type from the expression on the right of =. Therefore it will work with any type, the only requirement is to initialize the auto variable when declaring it so that the compiler can deduce the type.

auto 关键字从 = 右侧的表达式中获取类型。因此它适用于任何类型,唯一的要求是在声明它时初始化 auto 变量,以便编译器可以推断出类型。

Examples:

例子:

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

回答by Kirill V. Lyadvinsky

autokeyword is intended to use in such situation, it is absolutely safe. But unfortunately it available only in C++0x so you will have portability issues with it.

auto关键字就是在这种情况下使用的,绝对安全。但不幸的是,它仅在 C++0x 中可用,因此您将遇到可移植性问题。

回答by a o

This is new item in the language which I think we are going to be struggling with for years to come. The 'auto' of the start presents not only readability problem , from now on when you encounter it you will have to spend considerable time trying to figure out wtf it is(just like the time that intern named all variables xyz :)), but you also will spend considerable time cleaning after easily excitable programmers , like the once who replied before me. Example from above , I can bet $1000 , will be written "for (auto it : s)", not "for (auto& it : s)", as a result invoking move semantics where you list expecting it, modifying your collection underneath .

这是语言中的新项目,我认为我们将在未来几年内苦苦挣扎。start 的 'auto' 不仅存在可读性问题,从现在开始,当您遇到它时,您将不得不花费大量时间试图弄清楚它是什么(就像实习生将所有变量命名为 xyz 的时间 :)),但是你也会花大量时间清理容易兴奋的程序员,就像我之前回复的那个。上面的例子,我可以打赌 1000 美元,将被写成“for (auto it : s)”,而不是“for (auto& it : s)”,因此调用移动语义,你列出期望它,修改你下面的集合。

Another example of the problem is your question itself. You clearly don't know much about stl iterators and you trying to overcome that gap through usage of the magic of 'auto', as a result you create the code that might be problematic later on

问题的另一个例子是你的问题本身。您显然对 stl 迭代器知之甚少,并且您试图通过使用“自动”的魔力来克服这一差距,结果您创建了以后可能会出现问题的代码

回答by user11310689

If you want a code that is readable by all programmers (c++, java, and others) use the original old form instead of cryptographic new features

如果您想要所有程序员(c++、java 和其他人)都可读的代码,请使用原始的旧形式而不是加密的新功能

atp::ta::DataDrawArrayInfo* ddai;
for(size_t i = 0; i < m_dataDraw->m_dataDrawArrayInfoList.size(); i++) {
    ddai = m_dataDraw->m_dataDrawArrayInfoList[i];
    //...
}