What is the best best way to map two string values to one string
value.
say I need to map first_name, last_name to account_name. What is the
best way to implement that?
You can group the first and last name into a new Name class, overload
it's == operator to check if the first and last name match the first
and last name of the input Name object and put Name objects as keys in
the map. You can then do something like
std::string account = nameAccountMap[Name("Puzzle", "Cracker")];
to find the account name belonging to Puzzle Cracker.
Or you can introduce a Person class that holds all three and use
function objects to check if a Person object has a certain first name
and last name. This together with the STL's find_if function can give
you a Person object iterator that matches your first name and last
name.
Something like:
class Person
{
public:
std::string getFirstName();
std::string getLastName();
std::string getAccountName();
};
class HasPersonGotName
{
public:
HasPersonGotName(const std::string firstName, const std::string
lastName) :
firstName_(firstName), lastName_(lastName)
{
}
bool operator()(const Person* person) const
{
return ((firstName_ == person.getFirstName()) && (lastName_ ==
person.getLastName());
}
private:
std::string firstName_;
std::string lastName_;
};
void someFunc()
{
std::vector<Person*> persons;
// Assume some code fills your persons vector.
std::vector<Person*>::const_iterator = std::find_if(person.begin(),
person.end(), HasPersonGotName("Puzzle", "Cracker"));
if (it != persons.end())
{
std::cout << "Account found, account name is: " << (*it)->getAccountName() << std::endl;
}
else
{
std::cout << "Account not found." << std::endl;
}
}
Might seem a bit strange at first sight, but once you get the hang of
it, it helps a lot.
Good luck.