下面是其中可能的工作给予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)?
来源
2009-02-17 15:37:32
Guy
我删除了我的答案,因为我不认为足够的:)我认为特里将是理想的这个用例。只需沿着trie的路径移动,直到找不到更多匹配项目。看看这里:http://en.wikipedia.org/wiki/Trie。 – 2009-02-17 15:41:52