映射迭代器,字符串错误读取字符
问题描述:
我想在带有前缀的映射中进行部分匹配。映射迭代器,字符串错误读取字符
我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.
答
你想用find
方法:http://www.cplusplus.com/reference/unordered_map/unordered_map/find/
如果它是std::map
,则下限将标记项目本身(如果已存在)或可能添加它的位置(“插入提示”)。这对于高效的查找或插入操作很有用(您不需要再遍历树)。你只是在模拟find
已经做了什么,在这里(也就是说,如果它再次是std::map
)...
错误消息有可能来自调试器,而不是实际发生的事情。尝试输出got.first(在if之前) - 确保您期待匹配。 – kabanus
@kabanus我跟进了你的建议,并将结果添加到帖子的底部。当我研究时,有人指出,'lowerbound'应该能够匹配'key =“ABC 1234”'和'string =“ABC”'。 – BlooB
'unordered_map'没有lower_bound方法。 umap是什么类型的? – Curious