我想在帶有前綴的映射中進行部分匹配。映射迭代器,字符串錯誤讀取字符
我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的未有序圖
錯誤消息有可能來自調試器,而不是實際發生的事情。嘗試輸出got.first(在if之前) - 確保您期待匹配。 – kabanus
@kabanus我跟進了你的建議,並將結果添加到帖子的底部。當我研究時,有人指出,'lowerbound'應該能夠匹配'key =「ABC 1234」'和'string =「ABC」'。 – BlooB
'unordered_map'沒有lower_bound方法。 umap是什麼類型的? – Curious