在C ++中使用多个键进行映射 [英] Map with multiple keys in C++

查看:121
本文介绍了在C ++中使用多个键进行映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过它们的名称和索引来存储数据.换句话说,我想将string名称映射到对象,并为其自定义顺序.

I want to store data by both, their name and their index. In other words, I want to map string names to objects and also give them a custom order.

我首先想到的是std::vector键和对象对的std::vector对.顺序由向量中的位置给出.

What I came up with first is a std::vector of pairs of the string key and the object. The order was given by the position in the vector.

std::vector<std::pair<std::string, object> >

但是这种方法似乎不是最优的,因为它不会自动检查string名称的唯一性.此外,先按对象的顺序对对象进行分组是错误的,因为从逻辑上说,它们的一阶区别就是名称.

But this approach seems to be suboptimal since it doesn't automatically check for the uniqueness of string names. Moreover it feels wrong to group the objects by their order first, because logically their first order distinction is the name.

我需要一个允许通过名称和索引访问的数据结构.

I need a data structure that allows access by both name and index.

std::magic<std::string, unsigned int, object> collection;

// access by either string or unsigned int key
collection.insert("name", 42, new object());
collection["name"]
collection[42]

该用例是否已经有数据结构?如果没有,我该如何将它们放在一起,最好使用标准库?另外,我想一种在给定元素之后的位置插入新元素,而又不移动所有其他元素的方法.

Is there a data structure for this use case already? If not, how can I put one together, preferably using the standard library? Also I would like a way to insert new elements at the position after a given element without moving all further elements around.

推荐答案

Boost为此目的提供了一组容器,请参见:

Boost provides a set of containers just for this purpose, see: boost::multiindex

这篇关于在C ++中使用多个键进行映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆