映射复杂的查找操作

2022-01-20 00:00:00 find c++ map stl boost

我想做以下事情:
在字符串和任何类型的对象(可以是列表、整数 - 任何东西)之间定义映射.
地图的键可以如下(同样,这些值并不重要):
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) ?

相关文章