c++ boost库学习-05-双向映射容器bimap

STL中的map和 multimap都是单向映射只能通过key查找到value,但是实际项目开发中,有时也需要从value找到对应的key,boost的 bimap便是这样一种双映射容器它要求key,value都必须唯一。

使用需要包含头文件:

#include<boost/bimap.hpp> 

示例

#include<iostream>
using namespace  std;

//包含头文件
#include<boost/bimap.hpp>
using boost::bimap;

int main()
{
    
    
	
	bimap<int, string>  bi;
	//左视图,代表 key 类型是int , value 类型是string 
	bi.left.insert(std::make_pair<int, string>(1, "jack"));
	bi.left.insert(std::make_pair(2, "jay"));
	//右视图,代表 key 类型是string , value 类型是int
	bi.right.insert(std::make_pair("hello", 3));

	cout << "遍历\n";
	for (auto &node :bi.left)
	{
    
    
		cout << node.first << " " << node.second << endl;
	}
	cout << "查找\n";

	//查找
	auto  it = bi.left.find(2); //左视图的key为整形
	if (it != bi.left.end())
		cout << it->first << "~" << it->second << endl;

	auto it2 = bi.right.find("hello"); //右视图的key为字符串
	if (it2 != bi.right.end())
		cout << it2->first << "~" << it2->second << endl;
	
	
	system("pause");
	return 0;
}

结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/FairLikeSnow/article/details/130785377