code code - 5 days ago 6
C++ Question

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( auto i = data.begin(); i != data.end(); ) //Corrected! error was here... missing ()
{
if( (*i)->getName() == "cici" )
{
i = data.erase(i); //Corrected! Only works with C++11. i on left side is next valid pos.
//data.erase(i++); //Works always.
break;
}
else
++i;
}

Answer

Of course you use auto:

for( auto i = data.begin(); i != data.end() ; ) {  //  look at condition
    ...
} 

You could even use range-for if you wouldn't need the the iterator for erasure:

for (auto& sptr : data) {
    ...
}
Comments