我在我的项目中使用了 std::map
,因为我想将几个不同的字符串相互映射。例如,我可能会创建一个类似于此的 map :
std::map<std::string, std::string> map;
map["test"] = "Foo";
map["blah"] = "Drei";
map["fayh"] = "Najh";
// And so on...
我想使用比 map 中的键长的键来查找这些值,即部分匹配键。映射中的所有键与它们所比较的键共享相同的前缀
这就是我要实现的目标:
// Same map as earlier
std::cout << map.find('test123').second; // Should output 'Foo'
std::cout << map.find('test_2165').second; // Should output 'Foo' as well
std::cout << map.find('tes').second; // Key not found
std::cout << map.find('fayh_TK_Ka').second; // 'Najh'
我希望你明白我在追求什么。我想有效地检索映射到键的值,这些键对应于比它们大的比较键,但共享相同的前缀(例如“测试”)。
我不知道 std::map
是否是这种情况下的最佳选择,如果不是,请告知其他选项。
注意:我曾尝试使用带有 std::greater_equal
的映射作为关键比较器并结合 lower_bound
方法,但我最终遇到了运行时错误,而且我也质疑这种方法的效率。
最佳答案
以下将满足您的需要:
std::string my_find( const std::string& s )
{
auto it = map.lower_bound( s );
if( it != map.begin() ) {
if( it != map.end() && it->first == s ) return it->second; // exact match
--it;
if( it->first == s.substr( 0, it->first.size() ) ) {
return it->second;
}
}
return "Key not found";
}
关于c++ - 部分匹配 std::map 中的长键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19120916/