我需要为程序创建一个简单的查找函数,并希望确认完成任务的最佳方法。我有一个双列CSV文件,表示字符串(键)和双(值)对。该列表大约有3,000行/键值对。每次执行程序时,我都会在这个表上进行大约5,000次查找。下面是一些伪代码,接下来是几个问题:
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;
}
关于如何实现这一点的问题如下:
答案 0 :(得分:3)
// 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;
}
如果找不到密钥,则假定您更倾向于使用默认值而不是公开错误。
如果您想表明找不到该密钥,则在it == blah.end()
后find( )
时,您必须执行不同的操作。