【问题标题】:Struggling to create a Boost-Bimap containing std::bitset努力创建一个包含 std::bitset 的 Boost-Bimap
【发布时间】:2020-02-09 13:32:30
【问题描述】:

我有许多字符串及其等效的位集。我需要能够在两个方向上查找等价物,即“str to bitset”和“bitset to str”。我相信 boost-bimap 将是这项工作的正确容器。

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

整数示例有效:

#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 : 请参阅正在编译的类模板实例化 'boost::bimaps::bimap' 的参考

我不知道如何解决这个问题,如果有任何提示,我将不胜感激。

【问题讨论】:

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


    【解决方案1】:

    问题在于std::bitset 没有operator&lt; - 这是任何类似 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';
    }
    

    【讨论】:

    • 谢谢@Ayjay,效果很好。感谢快速回复。出于好奇,这是我应该能够从错误消息中收集到的东西吗?
    • 我从你的程序中得到的编译错误的第一行是error C2678: binary '&lt;': no operator found which takes a left-hand operand of type 'const _Ty' (or there is no acceptable conversion) with [ _Ty=std::bitset&lt;3&gt;]。老实说,我大多只是猜测这是问题所在,因为我很确定 bitset 没有operator&lt; 并且知道这是任何有序集合的要求。好消息是,在 C++20 中,语言中添加了一些概念,这将大大改善编译错误,类似于 Error: std::bitset&lt;3&gt; does not model Comparable
    • 感谢您的澄清。请问你用的是哪个编译器?
    • Visual Studio 2019
    猜你喜欢
    • 2019-01-13
    • 2014-10-13
    • 2016-09-03
    • 1970-01-01
    • 2021-03-03
    • 1970-01-01
    • 2020-10-17
    • 1970-01-01
    相关资源
    最近更新 更多