2014-03-04 60 views
1

我正在使用C++ 98。使用for_each/mem_fun有什麼問題

我有以下代碼:

#include <vector> 
#include <algorithm> 
#include <functional> 

struct Foo {}; 

void 
add_each(std::vector<std::vector<Foo*> > &vv, const Foo *f) 
{ 
    for_each(vv.begin(), vv.end(), std::bind2nd(std::mem_fun(&std::vector<Foo*>::push_back), f)); 
} 

基本上我喜歡的元件添加到每個矢量的末端。

G ++抱怨for_each這一行。

In file included from /usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/algorithm:62, 
       from 1.c:2: 
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/stl_algo.h: In function ‘_Funct std::for_each(_IIter, _IIter, _Funct) [with _IIter = __gnu_cxx::__normal_iterator<std::vector<Foo*, std::allocator<Foo*> >*, std::vector<std::vector<Foo*, std::allocator<Foo*> >, std::allocator<std::vector<Foo*, std::allocator<Foo*> > > > >, _Funct = std::binder2nd<std::mem_fun1_t<void, std::vector<Foo*, std::allocator<Foo*> >, Foo* const&> >]’: 
1.c:10: instantiated from here 
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/stl_algo.h:4200: error: no match for call to ‘(std::binder2nd<std::mem_fun1_t<void, std::vector<Foo*, std::allocator<Foo*> >, Foo* const&> >) (std::vector<Foo*, std::allocator<Foo*> >&)’ 
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/backward/binders.h:146: note: candidates are: typename _Operation::result_type std::binder2nd<_Operation>::operator()(const typename _Operation::first_argument_type&) const [with _Operation = std::mem_fun1_t<void, std::vector<Foo*, std::allocator<Foo*> >, Foo* const&>] 
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/backward/binders.h:152: note:     typename _Operation::result_type std::binder2nd<_Operation>::operator()(typename _Operation::first_argument_type&) const [with _Operation = std::mem_fun1_t<void, std::vector<Foo*, std::allocator<Foo*> >, Foo* const&>] 

你看到有什麼問題嗎?

回答

1

for_each將取消引用迭代器並將該結果傳遞給它的一元函數參數。在你的情況下,這種類型是std::vector<Foo*>&。然而,std::mem_fun需要指針指向其打包的對象,而不是參考。您應該改用std::mem_fun_ref

void 
add_each(std::vector<std::vector<Foo*> > &vv, const Foo *f) 
{ 
    for_each(vv.begin(), vv.end(), 
      std::bind2nd(std::mem_fun_ref(&std::vector<Foo*>::push_back), f)); 
} 

Live example

0

您正在嘗試將push_back a const Foo*轉換成矢量Foo*。使矢量保持const Foo*或將參數f的類型更改爲Foo*

0

如果你想你的代碼將與的C- 2011 ++話,我建議以下解決方案標準庫也編譯

void (std::vector<Foo *>:: *pf)(Foo * const &); 
pf = &std::vector<Foo *>::push_back; 

std::for_each(vv.begin(), vv.end(), 
       std::bind2nd(std::mem_fun_ref(pf), f)); 

的問題是,在C++ 2011成員函數push_back已超載。