【问题标题】:Implementing unordered maps in C++在 C++ 中实现无序映射
【发布时间】:2013-07-12 19:31:23
【问题描述】:

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

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

  1. 如何进行实际查找?我正在考虑一个简单的函数,它在传递(a)对我的地图的引用和(b)一个键时返回值。谁能提供一个简单的框架
  2. 我的字符串值是“可排序的”,因为它们是字母术语 - 我是否应该以某种方式将其放入有序列表中以促进更快的查找?
  3. 这种方法有意义吗?

【问题讨论】:

    标签: c++ map unordered


    【解决方案1】:
    // 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( ) 之后执行不同的操作。

    【讨论】:

    • 这看起来很棒 - 谢谢。我将尝试实施并回复任何问题或问题
    • 抱歉,这个项目被耽搁了——我已经完成了第一部分(将值从我的 CSV 文件加载到无序地图中),现在正在查找。会确认,但到目前为止情况看起来不错。再次感谢。
    • 第二部分有一些问题。我纠正了我认为的一些错别字(Tenate vs. Tenant,default vs. default_value),但我仍然遇到返回值问题(*it) - 我的编译器给了我一个类型转换错误(因为我应该要返回一个双精度,但它是一个无序的地图?)有什么想法吗?
    • 地图包含键值对。如果你想要这个值,it-&gt;second
    • 再次感谢。仍然没有为我编译 - 请参阅上面的修改后的代码 - 现在我收到“未解析的外部符号”错误 - 知道发生了什么吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-29
    • 1970-01-01
    • 2012-01-04
    • 2013-08-05
    • 2015-05-06
    • 2022-01-23
    • 1970-01-01
    相关资源
    最近更新 更多