I have a test map with pair of std::string and Person pointer

class MyMap {
public:
    void clear() {
       std::for_each(people.begin(), people.end(),std::bind1st(std::mem_fun(&MyMap::remove), this));
    }
    void remove(std::pair<std::string, Person*> p) { delete p.second; }
private:
    std::map<name, Person*> people;
};

My question is does for_each pass each Person pair by ref or value? is it worth using my own, this is a bit cleaner.

In addition to that if I want to use boost::bind or std::bind (c++11) instead of bind1st, how would I do it? should this function be like struct having operator() that inherits std::unary_function?

有帮助吗?

解决方案

The type of the map is std::map<name, Person*>, but the parameter for the remove function is std::pair<std::string, Person*>. This won't work unless name is typedef for std::string.

The way your remove function is currently defined, you'll make copies of the map's value_type. Change the function signature to:

void remove(std::pair<const std::string, Person *>& p)
//                    ^^^^^                       ^
//                    key must be const           take a reference

To use std::bind instead of std::bind1st

std::for_each( people.begin(), 
               people.end(), 
               std::bind( &MyMap::remove, this, std::placeholders::_1 ) );

But if you can use C++11 features, there's no need for std::bind, lambda is much nicer.

std::for_each( people.begin(), 
               people.end(), 
               []( decltype(*people.begin())& p ) { delete p.second; } );

or use a range based for loop

for( auto&& p : people ) {
    delete p.second;
}

其他提示

for_each will call the functor either by-value or by-reference, depending on how you have defined the functor.

For example:

struct Gizmo
{
  bool operator() (const Zippy& rhs) const
  {
    // ...
  }
};

This functor is call-by-ref. However:

struct Gizmo
{
  bool operator() (Zippy rhs) const
  {
    // ...
  }
};

This one is call-by-value.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top