2013-07-09 26 views
0

我有一对的std ::串和Person指针测试地图std :: for_each是按值还是按引用传递?

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; 
}; 

我的问题是确实的for_each通过ref或值传递每个人对?这是值得使用我自己的,这是一个更清洁。

除此之外,如果我想要使用boost :: bind或std :: bind(C++ 11)而不是bind1st,我该怎么做?这个函数应该像struct继承std :: unary_function的operator()吗?

+0

范围“的for_each通过ref或值传递每个人对”:通过在那里,如果你正在谈论的功能(第三个参数),这取决于如何?函数定义是。 –

+0

看着目前的功能。 for_each不接受签名'void remove(std :: pair &p)'抱怨超载 – abumusamq

+0

为什么重要?你所有的删除功能都会删除Person。 – Wug

回答

2

地图的类型是std::map<name, Person*>,但remove函数的参数是std::pair<std::string, Person*>。除非namestd::string的typedef,否则这将不起作用。

您当前定义的remove函数的方式,您将复制mapvalue_type。更改函数签名:

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

要使用std::bind代替std::bind1st

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

但是如果你能使用C++ 11点的特性,没有必要为std::bind,拉姆达是更漂亮。

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

或使用基于for循环

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

for_each将通过值或通过引用调用仿函数,具体取决于您如何定义仿函数。

例如:

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

这算符是调用 - REF。但是:

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

这是一个按价值计价。

+0

是的我知道,但通过这在std :: for_each导致编译错误 :13:需要从'无效MyMap :: clear()' ../src/ main.cc:45:34:从这里需要 /usr/include/c++/4.7/backward/binders。h:125:7:error:'typename _Operation :: result_type std :: binder1st <_Operation> :: operator()(typename _Operation :: second_argument_type&)const [with _Operation = std :: mem_fun1_t ; typename _Operation :: result_type = void; typename _Operation :: second_argument_type = Person *&]'不能超载 – abumusamq

+0

向我们显示'Person'和'name' –