Reputation: 411
I need to create a simple lookup function for a program and want to confirm the best way to accomplish the task. I have a two-column CSV file that represents a string (key) and double (value) pair. The list is about 3,000 rows / key-value pairs. I will be doing about 5,000 lookups on this table each time my program is executed. Some psuedo-code is below followed by a few questions:
CSV file - columns are "Tenant" and "PD"
// Declare an unordered map
unordered_map<string,double> TenantPDLookup;
// Read from CSV file into the map object - I can do this part
void ReadTenantLookup(unordered_map<string,double> TenantPDLookup) {...}
// Lookup the values (PD) based on a series of keys (Tenant)
// Here is my code that is not working (note this is a type string, string)
string GetTenantRating(string const& TenantName, Assumptions& Ass,
tenant_lookup_map const& TenantRatingLookup) {
auto TenantRating = TenantRatingLookup.find(TenantName);
if (TenantRating == TenantRatingLookup.end())
return Ass.DefaultTenantRating;
return TenantRating->second;
}
My questions about how to implement this are as follows:
Upvotes: 2
Views: 1000
Reputation: 275878
// Declare an unordered map
typedef std::unordered_map<std::string,double> pd_lookup_map;
pd_lookup_map TenantPDLookup;
// Read from CSV file into the map object - I can do this part
pd_lookup_map ReadTenantLookup() {
pd_lookup_map retval;
// read std::string and double from file
std::string key_from_file;
double value_from_file;
retval[key_from_file] = value_from_file;
// repeat for entire file
return retval; // is very efficient to return std containers by value
}
// Lookup the values (PD) based on a series of keys (Tenant)
// How do I do this part?
double GetTenantPD(unordered_map const& TenantPDLookup, std::string const& Key, double default_value = 0.0) {
auto it = TenatePDLookup.find(Key);
if (it == TenatePDLookup.end())
return default;
return *it;
}
This assumes you'd rather have a default value than expose an error if the Key is not found.
If you want to indicate that the key was not found, you'll have to do something different when it == blah.end()
after a find( )
.
Upvotes: 3