Dulgan
Dulgan

Reputation: 6694

Availability of bidictionary structure?

I'm facing a case in my application where I need a bidirectional dictionary data structure, that means a kind of NSDictionary where your can retrieve a key with a value and a value with a key (all values and keys are unique).

Is there such a kind of data structure in C / ObjectiveC ?

Upvotes: 2

Views: 408

Answers (2)

CouchDeveloper
CouchDeveloper

Reputation: 19174

Literally, the answer is No.

As a workaround you may create a helper class which manages two dictionaries.

Another approach is to create a thin wrapper around C++ container which implement this: boost's Bimap.

When using ARC and Objective-C objects as values or keys in C++ containers, they will handle NSObjects quite nicely. That is, they take care of memory management as you would expect - and you even get "exception safety" for free. Additionally, C++ standard containers are also a tad faster, use less memory, and provide more options to optimize (e.g. custom allocators).

Upvotes: 1

Rui Peres
Rui Peres

Reputation: 25927

You can do it with a NSDictionary:

allKeysForObject: Returns a new array containing the keys corresponding to all occurrences of a given object in the dictionary.

  • (NSArray *)allKeysForObject:(id)anObject Parameters anObject The value to look for in the dictionary. Return Value A new array containing the keys corresponding to all occurrences of anObject in the dictionary. If no object matching anObject is found, returns an empty array.

Discussion Each object in the dictionary is sent an isEqual: message to determine if it’s equal to anObject.

And:

objectForKey: Returns the value associated with a given key.

  • (id)objectForKey:(id)aKey Parameters aKey The key for which to return the corresponding value. Return Value The value associated with aKey, or nil if no value is associated with aKey.

Upvotes: 3

Related Questions