Sunday, 15 August 2010

c++ - Most efficient/fastest way to delete/remove items of a vector -



c++ - Most efficient/fastest way to delete/remove items of a vector -

there several ways delete/remove items of vector.

i have vector of pointers , need delete of them on deconstructor of class.

what efficient/fastest way or safest way?

// 1º std::for_each(vector.begin(), vector.end(), [] (object * object) { delete object; }); // 2º (int = 0; < vector.size(); ++i) { delete vector[i]; } // 3º (auto current = vector.begin(); current != vector.end(); ++current){ delete (* current); }

the safest way utilize either std::vector<std::unique_ptr<object>> or std::vector<std::shared_ptr<object>> depending on lifetime semantics need object instances.

either way, wouldn't need anything in destructor; vector's destructor destruct of smart pointer instances. in turn, automatically delete object instances according particular semantics: unique_ptr delete them immediately, while shared_ptr delete them no other shared_ptrs point object.

it's unlikely there faster way either, assuming need store pointers. (if don't need polymorphism, utilize std::vector<object> has 1 less level of indirection.)

c++

No comments:

Post a Comment