下面是其中可能的工作給予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