2017-06-22 97 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)...