我正在尝试使用 boost::bimap 来满足我的一项要求。下面是示例代码
typedef bimap<
multiset_of< string >,
multiset_of< string >,
set_of_relation<>
> bm_type;
bm_type bm;
assign::insert( bm )
( "John" , string("lazarus" ) )
( "Peter", string("vinicius") )
( "Peter", string("test") )
( "Simon", string("vinicius") )
( "John", string("viniciusa") )
( "John", string("vinicius") )
我想做一些事情,比如为 John 和 Peter 寻找匹配值,换句话说,John 和 Peter 的值之间的交集,例如:在这种情况下它将是 ("vinicius")。有人可以提供一些关注吗?
最佳答案
这是我最初想出的:
template <typename Value = std::string, typename Bimap, typename Key>
std::set<Value> projection(Bimap const& bm, Key const& key)
{
std::set<Value> p;
auto range = bm.left.equal_range(key);
auto values = boost::make_iterator_range(range.first, range.second);
for (auto& relation : values)
p.insert(relation.template get<boost::bimaps::member_at::right>());
return p;
}
auto john = projection(bm, "John");
auto peter = projection(bm, "Peter");
std::multiset<std::string> intersection;
std::set_intersection(
john.begin(), john.end(),
peter.begin(), peter.end(),
inserter(intersection, intersection.end())
);
我认为它可以更有效率。所以我尝试使用 Boost Range 的适配器动态替换投影:
struct GetRightMember
{
template <typename> struct result { typedef std::string type; };
template <typename T>
std::string operator()(T const& v) const {
return v.template get<boost::bimaps::member_at::right>();
}
};
const GetRightMember getright;
std::cout << "Intersection: ";
// WARNING: broken: ranges not sorted
boost::set_intersection(
bm.left.equal_range("John") | transformed(getright),
bm.left.equal_range("Peter") | transformed(getright),
std::ostream_iterator<std::string>(std::cout, " "));
很遗憾,它不起作用 - 大概是因为转换后的范围未排序。
所以我会坚持使用更冗长的版本(或者重新考虑我的数据结构选择)。见<强>Live On Coliru
关于c++ - 来自 boost::bimap 的各种值之间的交集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22216039/