这是 litb 答案的变体(以某种方式从答案列表中删除),考虑到“*”被删除,它可能会起作用:
template<typename Map> typename Map::const_iterator
find_prefix(Map const& map, typename Map::key_type const& key)
{
typename Map::const_iterator it = map.upper_bound(key);
while (it != map.begin())
{
--it;
if(key.substr(0, it->first.size()) == it->first)
return it;
}
return map.end(); // map contains no prefix
}
我忘了添加使用它的代码:
std::map<std::string, int> smap;
smap["AAA/"] = 1;
smap["BBB/"] = 2;
smap["AAA/AA"] = 3;
find_prefix(smap, "AAA/AB")->second; // ==> 1
find_prefix(smap, "AAA/AA")->second; // ==> 3
find_prefix(smap, "BBB/AB")->second; // ==> 2
find_prefix(smap, "CCC/AB"); // ==> smap.end()
有什么评论(感谢 litb)?