dimanche 27 novembre 2016

smart pointers and iterating with auto

Is it possible to use auto for iteration purposes as so?

Code produces error, but I wonder if maybe it is possible. Line with error is commented. I'm curious because I like smart pointers but I'd like to type less... and I like the idea of quick prototyping with c++.

        deque<shared_ptr<Vehicle>> data;
    data.push_back( shared_ptr<Vehicle>(new Vehicle("aba")) );
    data.push_back( shared_ptr<Vehicle>(new Vehicle("bobo")) );
    data.push_back( shared_ptr<Vehicle>(new Vehicle("cici")) );
    data.push_back( shared_ptr<Vehicle>(new Vehicle("dede")) );
    data.push_back( shared_ptr<Vehicle>(new Vehicle("efee")) );


    for(unsigned int i =0; i < data.size(); i++ )  //old scholl
    {
        cout << data.at(i)->getName() << endl;

    }

    data.pop_front();
    data.pop_back();


    for(deque<shared_ptr<Vehicle>>::iterator i = data.begin(); i != data.end(); )  //works
    {
        cout << (*i)->getName() << endl;
        ++i;
    }


    for( auto i = data.begin(); i != data.end; )   //error here
    {
        if( (*i)->getName() == "cici" )
        {
            i = list.erase(i);          //Only works with C++11. i on left side is next valid pos.  
            //list.erase(i++);          //Works always.
            break;
        }
        else
            ++i; 
    }

Aucun commentaire:

Enregistrer un commentaire