I am trying to come up with techniques of accessing/retrieving an object from a container (map, vector, ) in the most efficient manor possible.
So if I have the object:
class Person
{
public:
string name;
unsigned int ID; // unique ID
double deposit;
};
// And then I have a vector of pointers to person objects
std::vector <Person*> people;
Person* getPerson( string nName );
Person* getPerson( unsigned int nID ); // what would be a good method to quickly identify/retrieve the correct Person object from my vector?
My ideas:
This is the iterative solution that is not efficient:
Person* getPerson( string nName )
{
for (int i=0; i<people.size(); i++)
{
if (people[i]->name == nName ) { return people[i]; }
}
}
Another way: have 2 maps
map <string, Person*> personNameMap;
Person* getPerson( string nName )
{
return personNameMap[nName];
}
map <string, Person*> personIDMap;
Person* getPerson( unsigned int nID )
{
char id[2];
atoi( nID, id, 10 ); // or is it itoa?
return personNameMap[id];
}
Any other ideas how I could store & retrieve my objects from a collection in a fast & efficient manor?