C++ Boost库 Bimap双向映射容器

Boost库 Bimap容器

概述

Bimap是Boost库中提供的一种双向映射(bi-directional map)数据结构。在C++标准库中,std::mapstd::unordered_map只允许通过键来查找值,而boost::bimap允许同时通过键和值来查找对应的元素。

特点

  • 双向映射:可以通过键来查找值,也可以通过值来查找键。
  • 键和值都是唯一的:在boost::bimap中,每个键和每个值都必须是唯一的,就像在标准映射中键是唯一的一样。
  • 多个视图boost::bimap提供了多个视图,允许像操作标准映射一样操作键到值的映射(left视图)和值到键的映射(right视图)。

使用

声明

与标准的映射类似,通过尖括号指定映射键和值的类型

  // 头文件
  #include <boost/bimap.hpp>


  boost::bimap<int, std::string> bimap;

插入数据

boost::bimap插入数据要分左侧视图插入右侧视图插入

使用左侧视图插入时,与std::map类似,此时是以键到值的映射的方式插入数据的,值可以直接通过.letf.at(键)被访问到值的内容
通过左侧视图插入的数据也可以使用右侧访问,此时需要先通过.right.find(值)找到对应的迭代器,再通过->second访问对应的键

	// 通过左侧视图插入一个元素
	bimap.left.insert(std::make_pair(1, "one"));
	bimap.left.insert(boost::bimap<int, std::string>::left_value_type(2, "two"));

	// 左侧访问
	std::cout << "左侧访问 键 -> 值 :" << bimap.left.at(1) << std::endl; // one
	// 右侧访问  -- right.find获取的迭代器指向的实际上是 <"two", 2> 所以需要使用->second获取对应的键
	std::cout << "右侧访问 值 -> 键 :" << bimap.right.find("two")->second << std::endl;

使用右侧视图插入时,注意需要交换键和值的顺序,键应当在右边,通过右侧视图插入的数据,可以通过.right.at(值)访问键
左侧同理。

	// 通过右侧视图插入一个元素
	bimap.right.insert(boost::bimap<int, std::string>::right_value_type("three", 3));
	// 右侧访问
	std::cout << "右侧访问 值 -> 键 :" << bimap.right.at("three") << std::endl;
	// 左侧访问
	std::cout << "右侧访问 键 -> 值 :" << bimap.left.find(3)->second << std::endl;
  • 直接使用insert方法,这样会根据提供的pair的类型自动决定是在左侧视图还是在右侧视图插入
  bimap.insert(boost::bimap<int, std::string>::value_type(1, "one"));
  bimap.insert(std::make_pair(2, "two"));

其中boost::bimap<int, std::string>::value_type(1, "one")是bimap提供的一种构造键值对的方式,它是一种特定的类型value_type,与pair类似
注意,在使用左侧或右侧视图插入时,对应的类型value_type要修改成对应的left_value_typeright_value_type

posted @ 2024-12-11 15:47  风陵南  阅读(286)  评论(0)    收藏  举报