c++ - 来自 boost::bimap 的各种值之间的交集

标签 c++ boost boost-bimap

我正在尝试使用 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/

相关文章:

c++ - Gem5 中的 UART 通信与 ARM 裸机

c++ - 使用 multiset_of boost bimap 查找

c++ - 声明 C++ 中的冲突说明符

c++ - 通过与 bimap 键类型不同的类型在 boost::bimaps::bimap 中查找元素

C++ 前向声明(指针)- 访问成员

c++ - 抽象类的用户定义构造函数

android - 是否可以通过编译的二进制文件在 Android 中生成本地缓冲区溢出以获得 root 访问权限?

c++ - 如何使 boost::asio::serial_port_base::flow_control 使用硬件流控制?

c++ - 调用 boost::lock 的析构函数的效果?

boost - BLAS 和 CUBLAS