gpt4 book ai didi

c++ - 使用 for_each/mem_fun 有什么问题

转载 作者:太空宇宙 更新时间:2023-11-04 11:38:59 25 4
gpt4 key购买 nike

我正在使用 C++98。

我有以下代码:

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

基本上我喜欢在每个 vector 的末尾添加一个元素。

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&>]

你看到哪里不对了吗?

最佳答案

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

关于c++ - 使用 for_each/mem_fun 有什么问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22179699/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com