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

pet*_*ohn 21 c++ boost c++11 boost-bimap

我有这样一个bimap:

using MyBimap = boost::bimaps::bimap<
    boost::bimaps::unordered_set_of<A>,
    boost::bimaps::unordered_set_of<B>>;
Run Code Online (Sandbox Code Playgroud)

我想从静态初始化列表构造它,因为它可以为std::map:

MyBimap map{{a1, b1}, {a2, b2}, {a3, b3}};
Run Code Online (Sandbox Code Playgroud)

不幸的是,它不起作用,因为bimap不支持初始化列表,所以我尝试了一种解决方法.Boost的文档列出了以下构造函数:

 bimap();

 template< class InputIterator >
 bimap(InputIterator first,InputIterator last);

 bimap(const bimap &);
Run Code Online (Sandbox Code Playgroud)

所以我尝试了第二个,像这样:

std::vector<std::pair<A,B>> v{{a1, b1}, {a2, b2}, {a3, b3}};
MyBimap map(v.begin(), v.end());
Run Code Online (Sandbox Code Playgroud)

它也没用.文档并不完全清楚这个构造函数期望什么样的迭代器,但显然它不仅仅是std::pair<A, B>对象的迭代器.那么这个构造函数对这种bimap的期望是什么?

Emi*_*ier 26

我使用以下"工厂函数",它接受一个支撑初始化列表并返回一个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());
}
Run Code Online (Sandbox Code Playgroud)

用法:

auto myBimap = makeBimap<int, int>({{1, 2}, {3, 4}, {5, 6}});
Run Code Online (Sandbox Code Playgroud)


小智 12

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
     */
}
Run Code Online (Sandbox Code Playgroud)


Ric*_*ett 8

迭代器开始/结束应该是一系列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;
}
Run Code Online (Sandbox Code Playgroud)