code code - 1 year ago 84
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.

Answer Source

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) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download