Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use the auto keyword in C++ STL

Tags:

c++

c++11

stl

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?

like image 425
dato datuashvili Avatar asked Aug 08 '10 12:08

dato datuashvili


2 Answers

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.

like image 190
user1234567 Avatar answered Sep 19 '22 20:09

user1234567


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!

like image 26
UncleBens Avatar answered Sep 19 '22 20:09

UncleBens