jett
jett

Reputation: 1276

Traversal and Access via id implementation hash_map & vector

I am designing the core of my program and have various entities which I currently loop through to call update(). I have around ten vectors containing my objects, although this might grow to a much larger amount in future. I have just realized I will need to look these up via an id fairly regularly, so I am forced to loop through all elements to look for the correct id.

I am thinking of creating a hashmap that contains the id along with a pointer to the object itself. Is this the most efficient way to do this? The id's are semi random although they only increase throughout program, with each element in each of the lists having an unique id (each time one is assigned the id counter goes up). The elements in vectors now get removed and added often. I haven't worked much with hashmaps, other than a small bit in java, so I am unsure if this will be an efficient route to go. I believe the code will still be readable, but are there any options other than hash_map that would be better suited for this? Thanks

Upvotes: 0

Views: 96

Answers (1)

sandesh247
sandesh247

Reputation: 1676

I am not sure why you have 10 vectors - if the objects can be stored in one sorted vector, you may use binary_search to find the object (remember to sort it after every insert).

Of course, the hash_map also works, at the cost of space/memory.

Upvotes: 1

Related Questions