在C++中实现无序映射
Implementing unordered maps in C++
我需要为程序创建一个简单的查找函数,并希望确认完成任务的最佳方式。我有一个两列CSV文件,它表示字符串(键)和双精度(值)对。该列表大约有3000行/键值对。每次执行程序时,我将在这个表上进行大约5000次查找。下面是一些psuedo代码,后面是一些问题:
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;
}
我对如何实现这一点的问题如下:
- 如何进行实际查找?我正在考虑一个简单的函数,它在传递(a)对映射的引用和(b)键时返回值。有人能提供一个简单的框架吗
- 我的字符串值是"可排序的",因为它们是阿尔法项——我是否应该以某种方式将其放入有序列表中,以便于更快地查找
- 这种方法有意义吗
// 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;
}
这假设您宁愿有一个默认值,也不愿在找不到Key的情况下暴露错误。
如果要指示未找到密钥,则必须在find( )
之后使用it == blah.end()
时执行不同的操作。
相关文章:
- 递归无序映射
- 正在将无序映射设置为无序映射的值
- 智能指针作为无序映射键,并通过引用进行比较
- 打印无序映射的第二个元素,即集合
- 由并发无序映射查找线程调用的函数是否安全?
- 将大数字(10-12 位数字)存储在无序映射中<字符串,整数>
- 使用无序映射在STL中存储键值对
- 为C++中的无序映射获取给定输入键的错误值
- 将大型对象存储在无序映射中是否效率低下
- 在无序映射的结构化绑定中推导类型
- 使用无序映射进行错误索引
- 将一个向量对放在一个无序映射与一个映射中
- 如何在c++中修改无序映射中的每个值
- C++:使用一对(cpp_int,int)整数作为无序映射中的键(其中cpp_int是boost多精度整数)
- 将 [] 索引到无序映射时出现段错误
- 以std::字符串作为关键字,按字典顺序对一个无序映射进行排序
- 无序映射存储桶的节点大小
- 在无序映射<字符串上使用 find(),向量<string>>与 C++ 中的有序映射花费相同的时间
- 以三个无符号字符为关键字的无序映射
- 无序映射比c++中的映射慢吗