50

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131

5 Answers5

70

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

In C++11 you can write:

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

instead of

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

It has the same meaning.

Update: See the @Alnitak's comment also.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
user1234567
  • 3,991
  • 3
  • 19
  • 25
56

The auto keyword 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.

#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 auto keyword simply allows you to take advantage of this knowledge - if you (compiler) know the right type, just choose for me!

UncleBens
  • 40,819
  • 6
  • 57
  • 90
  • For STL work, auto has grown on me. It's very helpful when you want, for example, to test the return value of an STL function, and that return is a pair, or something obscure. Anyone know the compiler flag on GCC needed to turn on its support for auto? – user2548100 Dec 19 '13 at 00:23
14

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.

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
Karel Petranek
  • 15,005
  • 4
  • 44
  • 68
  • 13
    Though technically correct. I hope this becomes bad practice. If everybody just declares all their variables `auto` it will become hard for humans to read and understand (and we head down the road to untyped languages). The use of auto should be reserved for situations where we don't actually care about the type as long as it behaves in a manor that we want (for example iterators, we don't actually care what iterator we get as long as we can use it like an iterator). – Martin York Aug 08 '10 at 18:48
  • 1
    @Martin: No kidding, the first time I saw a block of `auto` variables I thought "please die fast." Like you said, it should be used in those sort of "gimme a variable, whatever type it is" situations, not that "declare a variable, and deduce it's type from it's initializer hehehehe!" trying to be tricky crap. – GManNickG Aug 10 '10 at 17:59
  • @sverkerw: No. I mean it is hard for humans to read. What is the type of c? Do I need to know. How does it affect my interpretation of the rest of the code. – Martin York Aug 25 '10 at 19:25
  • @LokiAstari: That problem is entirely wiped away by having a decent IDE that can just tell you the type when you hover over the 'auto'. It's not untyped - it's statically typed, with (very very simple) inference. – Claudiu Oct 17 '14 at 16:50
  • 1
    Actually it seems its becoming standard and it is better to use auto for most things. https://www.youtube.com/watch?v=xnqTKD8uD64 – Daniel Ryan Oct 01 '15 at 04:31
  • Not its not I argue that you want your code to be explicit and using auto makes deducing what the code is actually doing what the data your working on harder to read. Once the feature is done readability should the next important thing for maintenance auto should be used where its blatantly obvious or where the type does not matter but not blindly using it everywhere just because that guy said so. – Ray Garner Nov 10 '18 at 14:05
  • Will `auto b = std::vector();` cause unnecessary copying? – huang Jul 27 '23 at 22:24
3

auto keyword 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.

Kirill V. Lyadvinsky
  • 97,037
  • 24
  • 136
  • 212
-1

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

atp::ta::DataDrawArrayInfo* ddai;
for(size_t i = 0; i < m_dataDraw->m_dataDrawArrayInfoList.size(); i++) {
    ddai = m_dataDraw->m_dataDrawArrayInfoList[i];
    //...
}
  • 5
    *"cryptic new features"* Iterators were there for more than 20 years. And `auto` is 8 years old. :/ – HolyBlackCat Apr 04 '19 at 09:49
  • 1
    Also, the C++ range-based loop is *very* similar to Java's for loop, so readability for Java developers is actually improved using this constructs. – Dinei Jul 04 '19 at 13:52