is std::map what I need in this case ?
Hi,
I've got a resource manager. Each resource has an ID (an unsigned int which keeps incrementing) and is stored in a std::vector.
The rest of the program always uses ID. So when something need access to a given resource, I have to iterate through the vector and test each ID to return a pointer to the resource.
I would like to speed that up by having a sort of system in which I pass the ID, and it returns me the index in the std::vector in the fastest way.
I think std::map is what I need, but as I don't know the stl really well, I would know if there is something better for this job before using std::map.
Thx for any help.
Yes, you could certainly use a std::map. Just search for C++ map tutorial, or something similar on google, and you'll find many useful sites that explain how to use maps. You'd probably want to do something like
map<int, Resource> resources;
Where Resource is your resource class. There's no need to use a separate vector, as it would just be an unnecessary level of indirection.
Have fun using maps!
map<int, Resource> resources;
Where Resource is your resource class. There's no need to use a separate vector, as it would just be an unnecessary level of indirection.
Have fun using maps!
I would agree that a std::map would suit you quite perfectly in this case. But as Deniz has said, you do not need to do all of that vector stuff. Here's a little example:
So definitly take a look at maps, those methods are the simplest, but highly advised against! You will be using Iterators instead to handle that stuff. If you need a 'real example' one can be done, it's late now [wink]
class Resource{// ... stuff ...};// Resourcesmap<int, Resource*> resourceMap;Resource* r1 = new Resource;Resource* r2 = new Resource;Resource* r3 = new Resource;// ... fill in data ...// Old hackish, dangerous way to do an insert into a mapresourceMap[r1->id] = r1;resourceMap[r2->id] = r2;resourceMap[r3->id] = r3;// Then when you need to get a resourcesint id = 1;// Once again, Old hackish, dangerous way to do an insert into a mapResource* cur = resourceMap[id]
So definitly take a look at maps, those methods are the simplest, but highly advised against! You will be using Iterators instead to handle that stuff. If you need a 'real example' one can be done, it's late now [wink]
Yes, once you have familiarized yourself with std::map's functionality, you can look into using its insert and find functions etc. Also, look at how Drew_Benton has suggested to declare the map, he's using a pointer to a Resource object, which you will probably want to do. In fact you will have to if you're going to use polymorphism (i.e. using subclasses of Resource).
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement