首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >努力创建包含std::bitset的Boost-Bimap

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

Stack Overflow用户
提问于 2019-10-12 05:24:32
回答 1查看 84关注 0票数 2

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

我设法使它与字符串和整数一起工作,但我的字符串/位集bimap不编译。我使用的是VS2019和最新的boost版本。

整数示例工作:

代码语言:javascript
复制
#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示例无法编译:

代码语言:javascript
复制
#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';
}

位集示例创建以下编译器错误:

boost_test.cpp(20):消息:参见对正在编译的类模板实例化'boost::bimaps::bimap‘的引用

我不知道如何解决这一问题,并将非常感谢任何提示。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-10-12 05:53:48

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

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

代码语言:javascript
复制
#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';
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58351126

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档