若要在size_t和std::string之间获取bimap,其中有~常量(不超过散列和任何潜在冲突的成本),则需要使用无序集合:
#include <boost/bimap.hpp>
#include <boost/bimap/unordered_set_of.hpp>
#include <string>
#include <iostream>
#include <typeinfo>
int main(int argc, char* argv[]) {
typedef boost::bimap< boost::bimaps::unordered_set_of<size_t>, boost::bimaps::unordered_set_of<std::string> > StringMap;
StringMap map;
map.insert(StringMap::value_type(1,std::string("Cheese")));
map.insert(StringMap::value_type(2,std::string("Cheese2")));
typedef StringMap::left_map::const_iterator const_iter_type;
const const_iter_type end = map.left.end();
for ( const_iter_type iter = map.left.begin(); iter != end; iter++ ) {
std::cout << iter->first << " " << map.left.at(iter->first) << "\n";
}
}
返回:
1 Cheese
2 Cheese2
无序集是set的boost版本,它使用哈希表而不是树来存储元素,请参见
Boost Unordered docs
.
查看bimap示例中的评论
Bimap example
,我们有:
左映射视图的工作方式类似于std::无序映射<std::string,long>,
鉴于这个国家的名字,我们可以用它在固定的时间内搜寻人口