3

这有什么问题:

template <typename T>
std::list<T> & operator+=(std::list<T> & first, std::list<T> const& second)
{
    std::for_each(second.begin(), second.end(), boost::bind(&std::list<T>::push_back, first, _1));

    return first;
}

它编译得很好,但不起作用。

4

3 回答 3

6

您需要使用boost::ref通过引用传递参数/对象,否则 bind 创建一个内部副本。

std::for_each(
    second.begin(), second.end(),
    boost::bind(&std::list<T>::push_back, boost::ref(first), _1)
);
于 2011-05-21T18:32:40.800 回答
6

请注意,虽然 Cat Plus Plus 的解决方案对您有用,但在 C++03 中(在即将到来的标准版本中出现 if lambdas 之前)鼓励使用的方法是使用标准库算法和仿函数。不幸的是,在某些情况下,它们自己会变得非常复杂,但在这种情况下,我认为它们会产生更清晰的代码:

std::copy(second.begin(), second.end(), std::back_inserter(first));
于 2011-05-21T18:38:18.777 回答
3
std::list<T> ls;
std::list<T> ls0;
// ...
ls.insert(ls.end(), ls0.begin(), ls0.end());
于 2011-05-21T18:37:25.837 回答