2013-07-12 39 views
2

我需要爲程序創建一個簡單的查找函數,並且要確認完成任務的最佳方式。我有一個表示字符串(鍵)和雙(值)對的兩列CSV文件。該列表大約有3000行/鍵值對。每次執行程序時,我都會在該表上執行大約5,000次查找。一些僞代碼如下跟着幾個問題:在C++中實現無序映射

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. 這種方法有意義嗎?

回答

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()之後您必須做一些不同的事情。

+0

這看起來不錯 - 謝謝。我會嘗試實現並回發任何問題或問題 – brentf

+0

對不起,在這個項目上舉行 - 我已經得到了第一部分工作(從我的CSV文件中加載值到無序映射),現在正在查找。將確認但事情看起來很棒。再次感謝。 – brentf

+0

與第二部分有一些問題。我糾正了我認爲是一些錯別字(Tenate與Tenant,默認與default_value),但我仍然有問題的返回值(* it) - 我的編譯器給我一個類型轉換錯誤(因爲我被假定要返回一個雙,但它是一個無序的地圖?)任何想法? – brentf