c++ - 在 C++ 中实现无序映射

标签 c++ dictionary unordered

我需要为程序创建一个简单的查找函数,并希望确认完成任务的最佳方法。我有一个两列 CSV 文件,表示字符串(键)和 double (值)对。该列表大约有 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;
 }

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

  1. 如何进行实际查找?我正在考虑一个简单的函数,当传递(a)对我的 map 的引用和(b)一个键时返回值。有人可以提供一个简单的框架
  2. 我的字符串值是“可排序的”,因为它们是 alpha 术语 - 我是否应该以某种方式将其放入有序列表以促进更快的查找?
  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 时暴露错误。

如果您想指示未找到该 key ,则必须在 find( ) 之后执行 it == blah.end() 时执行不同的操作>.

关于c++ - 在 C++ 中实现无序映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17622674/

相关文章:

python - 在Python中比较同一字典中每个键的字典值

objective-c - 如何仅添加一次 MKOverlay?

c++ - 从 unordered_multiset 读取会导致崩溃

c++ - 使用 boost 命令行解析器处理未知命令

C++ 11 自动初始化

c++ - 使用 for_each 遍历以 NULL 结尾的字符串数组

c++ - 散列函数到无序容器的桶大小?

c++ - 传递指定最左侧模板参数的模板模板参数(无别名)

dictionary - Go中通过反射为struct成员赋值

列表类型圆圈的 HTML 特殊字符