Khach_Du_Lich's blog

By Khach_Du_Lich, 12 years ago, In English

I don't understand how "auto" work !! Can anyone explain it to me ?! Thank you very much.

  • Vote: I like it
  • -25
  • Vote: I do not like it

»
12 years ago, hide # |
 
Vote: I like it -30 Vote: I do not like it

tuong cai gi chu ham nay tao cung khong biet

»
12 years ago, hide # |
 
Vote: I like it 0 Vote: I do not like it

for example you have set <int> s;
you can write this
for (auto i:s)cout<<i<<" "; instance of for (set<int>::iterator i=s.begin();i!=s.end();i++)cout<<*i<<" "

  • »
    »
    12 years ago, hide # ^ |
     
    Vote: I like it 0 Vote: I do not like it

    range based for for (type var: collection) and auto keyword are actually not the same feature

»
12 years ago, hide # |
 
Vote: I like it +8 Vote: I do not like it

auto is a new concept (to what I remember) that came from C++11. The auto variable, when intialized (and assigned a value), is automatically given a type. For example, auto i = a.begin() with vector<int> a and you will have a std::vector<int>::iterator variable i. Useful isn't it?

Imagine

vector<int> a;
/*Some working code with the vector here*/
for (vector<int>::iterator i = a.begin(); i<a.end(); ++i) 
{
    /*Some code to work with the iterator here*/
}

will be replaced efficiently with

vector<int> a;
/*Some working code with the vector here*/
for (auto i = a.begin(); i<a.end(); ++i) 
{
    /*Some code to work with the iterator here*/
}

(well, think of a list rather than a vector.) Or, a little off-topic, this with C++11:

vector<int> a;
/*Some working code with the vector here*/
for (auto i: a) 
{
    /*Some code to work with the iterator here*/
}

There are also more things you can do with auto

auto i = 1e18; //Assigned as double
auto i = a.begin() + 3; //iterator
auto i = f; //Any type f is
auto sum(auto a, auto b) {
   return a+b;
}

Hope this helps ^_^

  • »
    »
    12 years ago, hide # ^ |
     
    Vote: I like it +13 Vote: I do not like it

    Regarding the example:

    vector<int> a;
    /*Some working code with the vector here*/
    for (auto i: a) 
    {
        /*Some code to work with the iterator here*/
    }
    

    AFAIK, i is not an iterator here but an actual value. So, for example to print it you would use something like cout << i; rather than cout << *i;.

    Also if a was a map, i would be of type pair, with with i.first being a key from the map and i.second being the value for that key.