c++ - 使用 bimap 中的键访问值

标签 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;

> error: ‘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> >}’ has no member named ‘at’ auto itt = numbers.right.at({100000,50000});

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

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

最佳答案

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

首先,请注意您的右 View 的类型multiset_of
如您所见here , multiset_of 的等效容器是 std::multimap并且后者没有成员函数at
因此,您无法在 multiset_of 上调用 at,这就是通过 .right 访问 map 的右侧 View 时得到的结果。
这个错误确实也很明显。

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

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

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

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

关于c++ - 使用 bimap 中的键访问值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41844614/

相关文章:

c++ - 对称访客模式

c++ - 从底层类型安全地转换枚举类

c++ - 检查字符串是否重复出现特定字符

c++ - 为什么 boost shared_ptr 原子操作会导致 SIGSEGV

c++ - 使用 boost::dynamic_bitset 作为键值对序列化 boost::bimap

c++ - 我如何以无序和可变的方式使用 boost::bimap?

c++ - 将 mpz_class 转换为 int

C++ 未声明的标识符(但已声明?)

visual-c++ - Visual C++ 11 在 CMake 生成的项目中找不到 Boost unit_test_framework 库

c++ - 努力创建包含 std::bitset 的 Boost-Bimap