Cleaning up an STL list/vector of pointers

后端 未结 15 1370
没有蜡笔的小新
没有蜡笔的小新 2020-11-28 21:41

What is the shortest chunk of C++ you can come up with to safely clean up a std::vector or std::list of pointers? (assuming you have to call delet

15条回答
  •  暖寄归人
    2020-11-28 22:25

    For std::list use:

    while(!foo.empty()) delete foo.front(), foo.pop_front();
    

    For std::vector use:

    while(!bar.empty()) delete bar.back(), bar.pop_back();
    

    Not sure why i took front instead of back for std::list above. I guess it's the feeling that it's faster. But actually both are constant time :). Anyway wrap it into a function and have fun:

    template
    void delete_them(Container& c) { while(!c.empty()) delete c.back(), c.pop_back(); }
    

提交回复
热议问题