地图复杂查找操作 [英] map complex find operation
问题描述
我想执行以下操作:
定义字符串和任何类型的对象之间的映射(可能是一个列表,整数 - 任何东西)。
地图可以如下(值再次不重要):
AAA / 123==> 1
AAA / ==> 2
BBB / ==> 3
CCC / *==> 4
CCC / 123==> 5
现在,我想找到给定以下字符串的正确值:
AAA / 123应该给出1.
AAA / 111应该给予2.
CCC / 111应该给予4.
CCC / 123应该给出5.
BBB / AAA / 123应该给予3.
I want to do the following:
Define a map between a string and any kind of object (may be a list, integer - anything).
The keys to the map can be as follow (the values are, again, not important):
"AAA/123" ==> 1
"AAA/" ==> 2
"BBB/" ==> 3
"CCC/*" ==> 4
"CCC/123" ==> 5
Now, the trick is I want to find the right values given the following strings:
"AAA/123" should give 1.
"AAA/111" should give 2.
"CCC/111" should give 4.
"CCC/123" should give 5.
"BBB/AAA/123" should give 3.
任何想法我怎么用C ++和STL / boost?
Any idea how I do that with C++ and possibly STL/boost ?
推荐答案
这是一个变体的litb答案(这在某些方面从答案列表中删除),可能会被删除*的工作:
Here's a variant of litb answer (which was somehow deleted from the answers list) which might work given the '*' is removed:
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
}
我忘了添加使用它的代码:
I forgot to add the code that uses it:
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)?
any comment (and thanks to litb) ?
这篇关于地图复杂查找操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!