How would I use for_each to delete every value in an STL map?

后端 未结 4 2111
执念已碎
执念已碎 2021-02-09 09:50

Suppose I have a STL map where the values are pointers, and I want to delete them all. How would I represent the following code, but making use of std::for_each? I\'m happy for

4条回答
  •  故里飘歌
    2021-02-09 10:45

    If at all possible, you should use smart pointers in your map.

    The use of smart pointers here removes the need to refactor and debug member deletion. One less memory management to worry about going forward. Any time I use new/delete I think really hard about whether that's needed. A personal "code smell" (per Martin Fowler), if you like.

    Of course, if your old code returns a map, then the for_each approach is probably your best bet - but if you had some hand in creating the map, I'd recommend using smart pointers.

提交回复
热议问题