2017-06-22 45 views
0

我想在帶有前綴的映射中進行部分匹配。映射迭代器,字符串錯誤讀取字符

keys類似於:"ABCD efg,1234"

values看起來像這樣:"qqwe,123123,asdad,2000,323232"

覺得我通過來匹配關鍵字符串爲"ABCD efg"

NOTE: the `map` deceleration is elsewhere. It is declered like the following: 
     std::unordered_map<std::string, std::string> umap; 

Code: 

std::unordered_map<std::string, std::string>::const_iterator Account::FindPrefix(const std::string& search_for) 
{ 
    std::unordered_map<std::string, std::string>::const_iterator got = umap.lower_bound(search_for); 

    if (got != umap.end()) 
    { 
     const std::string& key = got->first; 
     if (key.compare(0, search_for.size(), search_for) == 0) 
      return got; 
    } 
    return umap.end(); 
} 

編譯的代碼,但總是返回umap.end(),並且從來沒有返回got,所以我使用了調試器,我注意到,那constant iterator got得到值(<Error reading characters of string>,<Error reading characters of string>)

注:我沒有檢查,以確保我喂正確的值到map,似乎很好,因爲我可以看到它填充。注意2:在if語句之前,Kabanus建議輸出got。當它達到std::cout<<got->first;程序崩潰,我得到以下按摩:

Exception thrown at 0x57EF65F6 (msvcp140d.dll) in BankManagment.exe: 0xC0000005: Access violation reading location 0xCDCDCDCD. 

編輯: 我不知道爲什麼編譯器沒趕上與使用LOWER_BOUND的未有序圖 enter image description here

編輯: 以下是錯誤按摩decltype(請在帖子的評論) enter image description here

+2

錯誤消息有可能來自調試器,而不是實際發生的事情。嘗試輸出got.first(在if之前) - 確保您期待匹配。 – kabanus

+0

@kabanus我跟進了你的建議,並將結果添加到帖子的底部。當我研究時,有人指出,'lowerbound'應該能夠匹配'key =「ABC 1234」'和'string =「ABC」'。 – BlooB

+2

'unordered_map'沒有lower_bound方法。 umap是什麼類型的? – Curious

回答

0

你想用find方法:http://www.cplusplus.com/reference/unordered_map/unordered_map/find/

如果它是std::map,則下限將標記項目本身(如果已存在)或可能添加它的位置(「插入提示」)。這對於高效的查找或插入操作很有用(您不需要再遍歷樹)。你只是在模擬find已經做了什麼,在這裏(也就是說,如果它再次是std::map)...