我可以有一个带有两个键的类似地图的课程吗? [英] can I have a map-like class with TWO key?

查看:70
本文介绍了我可以有一个带有两个键的类似地图的课程吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的记录:

I have a record like this:

struct WORD
{
    int iID;
    char* pchWord;
    .
    .
    .
};


如果我想将记录保存在地图类中并在以后进行浏览,则可以只使用一个变量作为KEY来插入(),查找()等.但是有些时候,我想使用记录的ID来浏览记录以及它们的"pchWord"值; howwwwww


if I want to have my records in a map class and explore through them later, I can just have one variable as KEY to insert(), find(), and etc. But some times I like to explore through my records using their ID as well as their "pchWord" value; howwwwww

推荐答案

Richard已经提出了一种非常好的方法.这是一种更C语言的选择.

int iID替换为void* iID.您可以继续为其分配int 值而不会发生溢出(在32位和64位目标上).

现在,只需使用std::multimap来存储您的数据.它允许多个键映射到相同的值.

现在需要注意的是:您必须手动确保iID pchWord之间没有冲突.一种简单的方法是使用char[0]数组获取iID 值(使它们在进程内存空间中成为唯一地址).

也就是说,我本人更喜欢理查德的建议.认为我的建议纯粹出于学术目的(主要是出于实验目的).
Richard has already suggested a very good way to do this. Here''s a more C-ish alternative.

Replace the int iID with a void* iID. You can continue to assign int values to it without overflow (on 32 bit and 64 bit targets).

Now just use a std::multimap to store your data. It allows multiple keys to map to the same values.

Now here''s the caveat : you have to manually make sure that there are no collisions between iID and pchWord. A simple way to accomplish this is to use char[0] arrays to get the iID values (making them unique addresses in the process memory space).

That said, I''d prefer Richard''s suggestion myself. Consider my suggestion to be purely of academic interest (mostly for experimentation).


您可以自己实现所有功能,或者有两个地图,其中一个使用作为pchWord反之亦然的键.
You could implement all functionality yourself, or perhaps have two maps, one of which uses the iID as a key to the pchWord or vice versa.


这篇关于我可以有一个带有两个键的类似地图的课程吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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