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

标签 c++ boost std-bitset boost-bimap

我有一些字符串和它们的 bitset 等价物。我需要能够在两个方向上查找等价物,即“str to bitset”和“bitset to str”。我相信 boost-bimap 将是这项工作的合适容器。

我设法让它与字符串和整数一起使用,但我的字符串/位集 bimap 无法编译。我正在使用带有最新 boost 版本的 VS2019。

整数示例有效:

#include <boost/bimap.hpp>
#include <string>
#include <iostream>

int main()
{
    typedef boost::bimap<std::string, int> bimap_str_int_t;

    bimap_str_int_t bimap1;
    bimap1.insert(bimap_str_int_t::value_type("A", 1));
    std::cout << bimap1.left.at("A") << '\n';  //prints 1
    std::cout << bimap1.right.at(1) << '\n';   // prints A
}

Bitset 示例编译失败:

#include <boost/bimap.hpp>
#include <string>
#include <iostream>
#include <bitset>

int main()
{
    typedef std::bitset<3> bitset_t;
    typedef boost::bimap<std::string, bitset_t> bimap_str_bitset_t;

    bimap_str_bitset_t bimap2;
    bitset_t bits{ "010" };

    bimap2.insert(bimap_str_bitset_t::value_type("A", bits));
    std::cout << bimap2.left.at("A") << '\n';
    std::cout << bimap2.right.at(bits) << '\n';
}

bitset 示例会产生以下编译器错误:

boost_test.cpp(20): message : see reference to class template instantiation 'boost::bimaps::bimap' being compiled

我不确定如何解决这个问题,非常感谢任何提示。

最佳答案

问题是 std::bitset没有operator< - 任何类似 STL 的有序集合的要求之一。

要解决此问题,您需要提供一个比较函数 - 您可以尝试以下一种方法:

#include <boost/bimap.hpp>
#include <string>
#include <iostream>
#include <bitset>

typedef std::bitset<3> bitset_t;
struct compare_bitset {
    bool operator()(const bitset_t& x, const bitset_t& y) const {
        return x.to_ulong() < y.to_ulong();
    }
};

int main()
{
    using bitset_set = boost::bimaps::set_of<bitset_t, compare_bitset>;
    typedef boost::bimap < std::string, bitset_set> bimap_str_bitset_t;

    bimap_str_bitset_t bimap2;
    bitset_t bits{ "010" };

    bimap2.insert(bimap_str_bitset_t::value_type("A", bits));
    std::cout << bimap2.left.at("A") << '\n';
    std::cout << bimap2.right.at(bits) << '\n';
}

关于c++ - 努力创建包含 std::bitset 的 Boost-Bimap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58351126/

相关文章:

c++ - 为什么容器需要const

c++ - 获取最后执行的 return 语句的行

c++ - OpenCV中图像矩阵的子区域

c++ - 如何在 Mac OS X 上监视目录中的更改?

c++ - 使用带条件变量的锁

c++ - 将位集转换为带符号的

c++ - Boost Graph Library : How to use depth_first_visit, ColorMap 问题

c++ - 使用 Phoenix Bind 绑定(bind) boost 信号

c++ - 从包含十六进制数的 std::string 或 QString 创建 std::bitset 或 QBitArray

c++ - 计算多个 std::bitset<N> 中出现 1 的最快方法?