复杂的映射查找操作 [英] map complex find operation

查看:98
本文介绍了复杂的映射查找操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要做到以下几点:

定义一个字符串,任何类型的对象之间的映射(可能是一个列表,整数 - 任何东西)。

到地图的键可以是如下(该值是再次不重要):

AAA / 123==>

AAA /的==> 2

BBB /
的==>

CCC / *==>

CCC / 123==>

现在,关键是我想找到给出以下字符串正确的价值观:

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可能​​/提振?

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
}

我忘了补充使用它的code:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆