Skip to main content
gamedev.net
🔒 Locked

Dual map data structure

Started by Nairb Dec 11, 2008 at 6:54 PM 4 replies 1.3k views
Original Post
Nairb
Nairb
I'm looking for a type of data structure that allows quick lookup on both a key and value. Basically, the problem is as follows: I have an id, name, and dataID. There is a one to many mapping from dataID to (id, name) tuple. Because of what my program is doing, I want to key off of the (id, name) tuple when assigning, but when retrieving I'd like to be able to grab all the (id, name) tuples associated with a single dataID. My current idea, which feels rather icky, follows: I'd have two maps, map[ (id, name), dataID ] forward; map[ dataID, list[ (id, name) ] ] backward; When doing the assignment to forward, I would also push onto the back of backward. When doing the retrieval, I would retrieve the list of a given dataID from backward, iterate over that list performing my operation, and if the (id, name) pair isn't found in forward (because of some change in assignment), remove it from the list instead of acting on it. It feels to me like this is a problem someone else has faced, and that there's probably a more elegant solution, but I haven't been able to think of one. Ideas? (Edit: Note, I'm using C++. The restrictions of the project allow me a subset of STL, but I can't bring in other libraries ala boost). Cheers, --Brian
Sneftel
Sneftel
protuberant

Note: the library is rather standalone; if you can't include boost, you can just c&p it.

EDIT: fixed link

[Edited by - Sneftel on December 11, 2008 9:07:10 PM]
Nairb
Nairb
Where is that link supposed to point? Right now it looks like it's pointing back at this thread.
Sneftel
Sneftel
How odd. Fixed.
Nairb
Nairb
Ah, thank you.

It seems like this is not quite what I'm looking for, though. From the one minute tutorial, it seems like a bimap is used for a one-to-one mapping, whereas I have a one-to-many mapping. That is, with a bimap I get:

map[X,Y]
map[Y,X]

Whereas my needs call for:

map[X,Y]
map[Y, list[X]]

Or in my specific case, one (id, name) can correspond to only one dataID, but a single dataID can be used by different (id, name) pairs.

Or am I reading this wrong/misinterpreting something?

Cheers,
-Brian
iMalc
iMalc
An easy solution is to have both a map and a multimap. You could wrap the two up in a seperate class if you want. Whenever you insert or remove a pair, you put it into or take it out of both containers.

It's a very simple solution, but it does come at the cost of relatively high memory usage. You could start with this, and if memory usage becomes a problem, then you find something else.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.