使用bimap中的键访问值

时间:2017-01-25 06:09:59

标签: c++ boost boost-bimap

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

#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;
  

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

上述行不起作用。我还想知道是否可以通过仅使用配对密钥中的一个元素来获取访问权限,例如

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

1 个答案:

答案 0 :(得分:2)

文档已包含诊断问题所需的全部内容。

首先,请注意右视图的类型multiset_of
正如您所看到的heremultiset_of的等效容器是std::multimap,而后者没有成员函数at。 因此,您无法在at上调用multiset_of,这是您通过.right访问地图的右视图时获得的内容。
错误也非常清楚。

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

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

好吧,对.end()进行检查可能是一个好主意。

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