簡體   English   中英

boost multi_index-如果元素的類型為僅移動,如何將元素從一個容器添加到另一個容器?

[英]boost multi_index - how to add an element from one container to another if its type is move-only?

我有:

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

但是它不能編譯,就像我嘗試過的許多其他方法一樣。

您可以使用該答案中概述的技巧: 從boost multi_index數組移動元素 (我在上一個問題上將其鏈接到該數組 )。

生活在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 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM