映射复杂的查找操作

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) ?

这篇关于映射复杂的查找操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)