如何从静态列表构造Boost bimap?

 廖蓉以 发布于 2023-02-13 19:00
3 个回答
  • C++初学者:你可以使用boost :: assign来生成初始化.我在这里找到了解决方案.

    例:

    #include <boost/bimap.hpp>
    #include <boost/assign.hpp>
    
    //declare the type of bimap we want
    typedef boost::bimap<int, std::string> bimapType;
    //init our bimap
    bimapType bimap = boost::assign::list_of< bimapType::relation >
    ( 1, "one"   )
    ( 2, "two"   )
    ( 3, "three" );
    
    //test if everything works
    int main(int argc, char **argv)
    {
        std::cout << bimap.left.find(1)->second << std::endl;
        std::cout << bimap.left.find(2)->second << std::endl;
        std::cout << bimap.left.find(3)->second << std::endl;
        std::cout << bimap.right.find("one")->second << std::endl;
        std::cout << bimap.right.find("two")->second << std::endl;
        std::cout << bimap.right.find("three")->second << std::endl;
    
        /* Output:
         * one
         * two
         * three
         * 1
         * 2
         * 3
         */
    }
    

    2023-02-13 19:02 回答
  • 我使用以下"工厂函数",它接受一个支撑初始化列表并返回一个boost::bimap:

    template <typename L, typename R>
    boost::bimap<L, R>
    makeBimap(std::initializer_list<typename boost::bimap<L, R>::value_type> list)
    {
        return boost::bimap<L, R>(list.begin(), list.end());
    }
    

    用法:

    auto myBimap = makeBimap<int, int>({{1, 2}, {3, 4}, {5, 6}});
    

    2023-02-13 19:02 回答
  • 迭代器开始/结束应该是一系列bimap值.

    boost::bimap< A, B>::value_type

    bimap值很像std :: pair,可以用{a1, b1}语法初始化.它们的向量似乎也可以工作,它为构造函数提供了可用的迭代器.

    好的,这是一个为我编译和运行的例子(gcc 4.8.2 --std = c ++ 11)

    #include <vector>
    #include <boost/bimap.hpp>
    
    using namespace std;
    int main() {
        typedef boost::bimap< int, int > MyBimap;
    
        std::vector<MyBimap::value_type > v{{1, 2}, {3, 4}, {5, 6}};
    
        MyBimap M(v.begin(),v.end());
    
        std::cout << "The size is " << M.size()
                  << std::endl;
    
        std::cout << "An entry is 1:" << M.left.at(1)
                  << std::endl;
    }
    

    2023-02-13 19:03 回答
撰写答案
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有