Alternative to auto

I have a sample code that uses auto. The thing is I don't know what auto does, even after looking at online resources.

Can anyone give me an alternative to the function, or explain what auto is doing in this function.

1
2
3
4
5
6
7
8
    int n;
    cin >> n;
    vector<int> input(n);

    for(auto &i : input) {
        cin >> i;
    }
auto is a C++11 feature that deduces the type of the variable (at compile-time).
In this instance, it deduces auto to be an int, so i is a reference to an int.

Your code would behave exactly the same if you replaced "auto" with "int".
Okay,

for this part (auto &i : input) what does the : do?
its a ranged based for loop: this is similar to:

for( int* ip = &input[0]; ip< &input[input.size()-1]; ip++)
cin >> *ip;

or, in english, 'loop over everything in input' which in your case is 'n' items.

this is an over-use / bad-use of auto IMHO. Auto exists to give you quickly confounding types that arise from iterators and other complicated derived types, not to replace things like 'int'.
ranged based for loops, however, are nice: I suspect they may be better optimized (the compiler can't always guess if the loop variable is needed in a regular loop).
Last edited on
Perfect, thank you
I disagree with jonnin’s assessment. auto is perfect for this kind of stuff. Suppose later you wish to change your input to be a vector of double, you no longer have to hunt down all the places where all you want is to iterate over them to change the types. Just change it in one spot, then let the compiler sort it out for you.

Last edited on
I'm with Duthomas on this one; this is exactly where auto is perfect. The whole point of the for loop here is that my meaning is "for every element in this container". I'm communicating forwards with the maintainer that I don't actually care at this point what kind of type that element is - I mean "whatever kind of element this container is". That decision was made back when the container was created; now I just mean "for all the elements in the container."

If I specified the type, if I specified int* , I'm saying to the maintainer "I really care that this is a <specified type> object, no matter what kind of element actually is in the container".
Last edited on
I can see that way of thinking, and ok, it makes sense at some level. I am just cautious with auto, as too much of not knowing what anything is quickly becomes a big pain to debug and read. Maybe its just me getting old, and wanting to know what something IS.
I can definitely agree that this sort of thing is a travesty:

auto x = function();

No idea what x is. No clues from where it came from. Almost certainly care very much what kind of object x is, even if only to be able to pass it onwards.

Topic archived. No new replies allowed.