boost multi_index - 如果一个元素的类型是仅移动的,如何将元素从一个容器添加到另一个容器?

时间:2018-05-26 23:59:15

标签: c++ boost

我有:

struct foo {
    ...
    std::unique_ptr<Bar> bar; // requires foo to be move-only
    foo() { bar = std::make_unique<Bar>(); }
    foo(foo&&) = default;
};

typedef boost::multi_index_container<
    foo,
    boost::multi_index::indexed_by< 
        boost::multi_index::random_access<>,
        boost::multi_index::hashed_unique<
            boost::multi_index::composite_key<
                foo,
                boost::multi_index::member<X,std::string,&X::zoo>,
            >
        >
    >
> MyContainerType;

这个MyContainerType的两个容器:

MyContainerType c1, c2;

在某些时刻,我想迭代所有c1元素,并将其中一些(根据一些逻辑)添加到c2。 我试过了:

for (auto it = c1.begin(); it != c1.end(); ++it) {
    if (...some logics... ) {
        c2.push_back(std::move(*it));
    }
}

但它没有编译,就像我尝试的其他方法一样。

1 个答案:

答案 0 :(得分:0)

您可以使用该答案中列出的技巧:Move element from boost multi_index array(我将您链接到上一个问题)。

<强> Live On Coliru

#include <boost/multi_index_container.hpp>
#include <boost/multi_index/sequenced_index.hpp>
#include <boost/optional.hpp>
#include <iostream>

// move-only
struct foo {
    foo(int x) : x(x) {}
    foo(foo&&)      = default;
    foo(foo const&) = delete;
    foo& operator=(foo&&)      = default;
    foo& operator=(foo const&) = delete;

    int x;
};

template <typename Container>
void dump(std::ostream& os, Container const& c) { 
    for (auto& r: c) os << r.x << " ";
    os << "\n";
}

static_assert(not std::is_copy_constructible<foo>{}, "foo moveonly");

namespace bmi = boost::multi_index;

using foos = bmi::multi_index_container<foo, bmi::indexed_by<bmi::sequenced<> > >;

int main() {
    foos source, other;

    source.emplace_back(1);
    source.emplace_back(2);
    source.emplace_back(3);
    source.emplace_back(4);
    source.emplace_back(5);
    dump(std::cout << "Source before: ", source);

    for (auto it = source.begin(); it != source.end();) {
        if (it->x % 2) { // odd?
            boost::optional<foo> extracted;

            if (source.modify(it, [&](foo& v) { extracted = std::move(v); })) {
                it = source.erase(it);
            } else {
                ++it;
            }
            other.push_back(std::move(*extracted));
        } else {
            ++it;
        }
    }

    dump(std::cout << "Source after: ", source);
    dump(std::cout << "Other after: ", other);
}

这会将奇数项从source移到other

Source before: 1 2 3 4 5 
Source after: 2 4 
Other after: 1 3 5