c++ - 部分匹配 std::map 中的长键

标签 c++ algorithm c++11 map std

我在我的项目中使用了 std::map,因为我想将几个不同的字符串相互映射。例如,我可能会创建一个类似于此的 map :

std::map<std::string, std::string> map;

map["test"] = "Foo";
map["blah"] = "Drei";
map["fayh"] = "Najh";
// And so on...

我想使用比 map 中的键长的键来查找这些值,即部分匹配键。映射中的所有键与它们所比较的键共享相同的前缀

这就是我要实现的目标:

// Same map as earlier
std::cout << map.find('test123').second;    // Should output 'Foo'
std::cout << map.find('test_2165').second;  // Should output 'Foo' as well
std::cout << map.find('tes').second;        // Key not found
std::cout << map.find('fayh_TK_Ka').second; // 'Najh'

我希望你明白我在追求什么。我想有效地检索映射到键的值,这些键对应于比它们大的比较键,但共享相同的前缀(例如“测试”)。

我不知道 std::map 是否是这种情况下的最佳选择,如果不是,请告知其他选项。

注意:我曾尝试使用带有 std::greater_equal 的映射作为关键比较器并结合 lower_bound 方法,但我最终遇到了运行时错误,而且我也质疑这种方法的效率。

最佳答案

以下将满足您的需要:

std::string my_find( const std::string& s )
{
    auto it = map.lower_bound( s );
    if( it != map.begin() ) {
        if( it != map.end() && it->first == s ) return it->second; // exact match
        --it;
        if( it->first == s.substr( 0, it->first.size() ) ) {
            return it->second;
        }
    }
    return "Key not found";
}

关于c++ - 部分匹配 std::map 中的长键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19120916/

相关文章:

c++ - 非本地 IP 的套接字监听器不起作用

algorithm - 撕纸效果(将矩形分成随机形状)

具有任意维度的一般精度的 quickhull 的 C++ 实现

algorithm - 分析时间复杂度时log base 2等于log base 3?

c++ - 无法将临时对象作为引用传递

c++ - 根据成员容器的大小专门化成员函数

c++ - DirectShow 网络摄像头录制

c++ - QT在QGraphicsScene上绘制富文本

c++ - 链接器错误 - undefined reference

c++ - 在运行时使用用户定义的文字