在C++中实现无序映射

Implementing unordered maps in C++

本文关键字:无序 映射 实现 C++      更新时间:2023-10-16

我需要为程序创建一个简单的查找函数,并希望确认完成任务的最佳方式。我有一个两列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;
 }

我对如何实现这一点的问题如下:

  1. 如何进行实际查找?我正在考虑一个简单的函数,它在传递(a)对映射的引用和(b)键时返回值。有人能提供一个简单的框架吗
  2. 我的字符串值是"可排序的",因为它们是阿尔法项——我是否应该以某种方式将其放入有序列表中,以便于更快地查找
  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;
}

这假设您宁愿有一个默认值,也不愿在找不到Key的情况下暴露错误。

如果要指示未找到密钥,则必须在find( )之后使用it == blah.end()时执行不同的操作。