What container to choose
I thought about storing some objects ... and now I don't know what to choose.
So, now I have such code:
std::map<std::string, Object*> mObjects;
But, as I was told here before, it's slow due to allocation of std::string
in each searching, so the key should be integer.
Why did I chose std::string
as key? Because it's very easy to access objects by their name, for example:
mObjects["SomeObj"];
So my first idea is:
std::map<int, Object*> mObjects;
and key is an CRC of object name:
mObjects[CRC32("SomeObject")];
But it's a bit unstable. And I know there is special hash-ma开发者_如何学Gops for this.
And the last, I have to sort my objects in map using some Compare
function.
Any ideas about container I can use?
So again, the main points:
- Accesing objects by string, but keyshould be integer, not string
- Sorting objects in map by some function
p.s. boost usage is permissible.
I can't say for sure, but are you always accessing items in the map by a literal string? If so, then you should just use consecutive enumerated values with symbolic names, and an appropriately sized vector
.
Assuming that you won't know the names until runtime 1000 items in the map seems really small for searching to possibly be a bottleneck. Are you sure that the lookup is the performance problem? Have you profiled to make sure that is the case? In general, using the most intuitive container is going to result in better code (because you can grasp the algorithm more easily) code.
Does your comment about constructing strings imply that you passing C-strings into the find function over and over? Try to avoid that by using std::string
consistently in your application.
If you insist on using the two-part approach: I suggest storing all your items in a vector
. Then you have one unordered_map
from string to index and another vector
that has all the indexes into the main container. Then you sort this second container of indexes to get the ordering you need. Finally, when you delete items from the master container you'll need to clean up both of the other two referencing containers.
精彩评论