【问题标题】:Access value with key in bimap使用 bimap 中的键访问值
【发布时间】:2017-01-25 06:09:59
【问题描述】:

我正在尝试获取通过其键访问的值。到目前为止,我有一个最小的示例,并且仅适用于左侧访问。

#include <string>
#include <iostream>
#include <utility>
#include <boost/bimap.hpp>
#include <boost/bimap/set_of.hpp>
#include <boost/bimap/multiset_of.hpp>

namespace bimaps = boost::bimaps;
typedef boost::bimap<bimaps::set_of<unsigned long int>,
        bimaps::multiset_of<std::pair<unsigned long int, unsigned long int> > > bimap_reference;
typedef bimap_reference::value_type position;
bimap_reference numbers;

int main()
{
    numbers.insert(position(123456, std::make_pair(100000,50000)));
    numbers.insert(position(234567, std::make_pair(200000,80000)));
    numbers.insert(position(345678, std::make_pair(300000,10000)));
    numbers.insert(position(456789 ,std::make_pair(100000,60000)));


    auto it = numbers.left.at(123456);
    std::cout<<"numbers:"<<it.first<<"<->"<<it.second<<std::endl;
    return 0;
}

当我尝试使用配对键从右侧查看值时,作为线索,我尝试了以下操作。

auto itt = numbers.right.at({100000,50000});
auto itt = numbers.right.at(std::make_pair(100000,50000));
std::cout<<"from right: "<<itt.first<<std::endl;

> 错误:'boost::bimaps::bimap, boost::bimaps::multiset_of >::right_map {aka class boost::bimaps::views::multimap_view, boost::bimaps::multiset_of >, mpl_::na , mpl_::na, mpl_::na> >}' 没有名为 'at' 的成员 auto itt = numbers.right.at({100000,50000});

以上行不工作。我也想知道是否可以通过仅使用配对键的一个元素来获得访问权限,例如

auto itt = numbers.right.at({50000});

【问题讨论】:

    标签: c++ boost boost-bimap


    【解决方案1】:

    文档已经包含诊断问题所需的所有内容。

    首先,注意你右视图的typemultiset_of
    如您所见heremultiset_of 的等效容器是std::multimap,而后者没有成员函数at
    因此,您不能在multiset_of 上调用at,这就是您通过.right 访问地图的正确视图时得到的结果。
    错误也很明显。

    您可以使用find 来获取您要查找的对象的迭代器:

    auto itt = numbers.right.find(std::make_pair(100000,50000));
    std::cout<<"from right: "<<itt->first.first <<std::endl;    
    

    嗯,对照.end() 检查它可能是个好主意。

    不,您不能使用半个键作为参数进行搜索。如果您想做这样的事情,您应该使用类似地图的东西,其中键是对的第一个元素,值是这些对的列表或其他一些非常适合您的实际问题的数据结构。
    bimap 绝对(几乎)不可行,不值得。

    【讨论】:

    • 感谢您的回答。其实我想用.at() 来快速访问。使用 .find() 可能不会那么快,因为 bimap 太大了。如果我不能用半参数搜索,那就是工作加倍,因为我的工作是用半搜索完成的。您能否建议具有此类功能的数据结构,确实很快。
    • 为答案添加了更多详细信息。我的两分钱:如果您想使用multiset_of,请使用find,除非您可以证明性能对您不利。话虽如此,您不能将atmultiset_of 一起使用,它没有该成员函数。这不是偏好问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-22
    • 2014-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-29
    相关资源
    最近更新 更多