C++ STL – Using the auto Keyword

c++c++11stl

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?

Best Answer

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.

Related Question