[英]Merge two boost intrusive sets in C++?
我有兩個Boost Intruset集,需要將其合並在一起。 我有map_old.m_old_attributes
boost侵入式集合,我需要將其合並到m_map_new_attributes
boost侵入式集合
void DataTest::merge_set(DataMap& map_old)
{
// merge map_old.m_old_attributes set into m_map_new_attributes
}
做這個的最好方式是什么? 我找不到可以為我合並的功能? 我最近開始使用Boost侵入式集,但找不到能夠進行合並的預定義方法,或者我錯了嗎?
的確,侵入性集合是另一種野獸。 他們不管理元素分配。
因此,合並時需要確定其含義 。 我想說的是一種合理的解釋,那就是您要將map_old
容器中包含的元素移到 DataMap中。
這將使map_old
空。 這是一個這樣的算法:
template <typename Set>
void merge_into(Set& s, Set& into) {
std::vector<std::reference_wrapper<Element> > tmp(s.begin(), s.end());
s.clear(); // important! unlinks the existing hooks
into.insert(tmp.begin(), tmp.end());
}
更新或者,您也可以使用稍微復雜一點的iterater-erase循環(小心迭代變量容器)來解決O(1)內存復雜性問題:還可以在Coliru上運行
for (auto it = s.begin(); it != s.end();) { auto& e = *it; it = s.erase(it); into.insert(e); }
#include <boost/intrusive/set.hpp>
#include <boost/intrusive/set_hook.hpp>
#include <string>
#include <vector>
#include <functional>
#include <iostream>
namespace bive = boost::intrusive;
struct Element : bive::set_base_hook<> {
std::string data;
Element(std::string const& data = "") : data(data) {}
bool operator< (Element const& rhs) const { return data < rhs.data; }
bool operator==(Element const& rhs) const { return data ==rhs.data; }
};
using Set = bive::set<Element>;
template <typename Set>
void merge_into(Set& s, Set& into) {
std::vector<std::reference_wrapper<Element> > tmp(s.begin(), s.end());
s.clear(); // important! unlinks the existing hooks
into.insert(tmp.begin(), tmp.end());
}
int main() {
std::vector<Element> va {{"one"},{"two"},{"three"},{"four"},{"five"},{"six"},{"seven"},{"eight"},{"nine"} };
Set a;
for(auto& v : va) a.insert(v);
std::vector<Element> vb {{"two"},{"four"},{"six"},{"eight"},{"ten"} };
Set b;
for(auto& v : vb) b.insert(v);
assert(9==a.size());
assert(5==b.size());
merge_into(a, b);
assert(a.empty());
assert(10==b.size());
}
當然,您可以為合並操作提供不同的語義(這將更類似於“復制”而不是“移動”)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.