如何创建/使用boost::multi_index实现键与映射类型无关的双键容器
用Boost.MultiIndex实现双键映射容器
首先,由于你的mapped_type本身不包含键(key1_type和key2_type),需要先定义一个包含键与值的元素结构体:
#include <boost/multi_index_container.hpp> #include <boost/multi_index/ordered_index.hpp> #include <boost/multi_index/member.hpp> #include <utility> #include <string> #include <iostream> using key1_type = double; using key2_type = int; using mapped_type = std::pair<std::string, std::string>; // 定义包含键和值的元素类型 struct Element { key1_type key1; key2_type key2; mapped_type value; }; std::ostream& operator<<(std::ostream& os, const mapped_type& e) { os << e.first << " " << e.second; return os; } // 补全容器定义 using Container = boost::multi_index_container< Element, boost::multi_index::indexed_by< // 第一个索引:按key1_type有序、唯一 boost::multi_index::ordered_unique< boost::multi_index::member<Element, key1_type, &Element::key1> >, // 第二个索引:按key2_type有序、唯一 boost::multi_index::ordered_unique< boost::multi_index::member<Element, key2_type, &Element::key2> > > >;
main函数中的操作示例
1. 向容器中添加元素
直接使用emplace或insert方法添加元素,注意ordered_unique索引要求每个key1和key2不能重复:
int main() { Container c; // 方式1:直接构造元素插入 c.emplace(3.14, 100, {"Alice", "Smith"}); c.emplace(2.71, 200, {"Bob", "Johnson"}); c.emplace(1.61, 300, {"Charlie", "Brown"}); // 方式2:构造Element对象后插入 Element e{0.57, 400, {"David", "Wilson"}}; c.insert(e); // 重复键插入会失败 auto [it, success] = c.emplace(3.14, 500, {"Duplicate", "Key1"}); if (!success) { std::cout << "插入失败:key1=3.14已存在\n"; }
2. 按key1_type或key2_type键值输出所有元素
通过get<索引序号>()获取对应索引,遍历输出:
// 按key1的顺序输出元素 std::cout << "\n按key1顺序输出:\n"; const auto& idx_key1 = c.get<0>(); for (const auto& elem : idx_key1) { std::cout << "key1: " << elem.key1 << ", value: " << elem.value << "\n"; } // 按key2的顺序输出元素 std::cout << "\n按key2顺序输出:\n"; const auto& idx_key2 = c.get<1>(); for (const auto& elem : idx_key2) { std::cout << "key2: " << elem.key2 << ", value: " << elem.value << "\n"; }
3. 通过key1_type或key2_type的键值获取元素内容
使用对应索引的find方法查找,通过迭代器判断是否找到并访问元素:
// 通过key1查找 double target_key1 = 2.71; auto it_key1 = idx_key1.find(target_key1); if (it_key1 != idx_key1.end()) { std::cout << "\n找到key1=" << target_key1 << " 对应的value:" << it_key1->value << "\n"; } else { std::cout << "\n未找到key1=" << target_key1 << "\n"; } // 通过key2查找 int target_key2 = 300; auto it_key2 = idx_key2.find(target_key2); if (it_key2 != idx_key2.end()) { std::cout << "找到key2=" << target_key2 << " 对应的value:" << it_key2->value << "\n"; } else { std::cout << "未找到key2=" << target_key2 << "\n"; } return 0; }
内容的提问来源于stack exchange,提问作者Alex Net
相关产品推荐
相关产品推荐

