在映射中查找部分字符串匹配项

To find partial string match in map

本文关键字:字符串 串匹配 字符 映射 查找部      更新时间:2023-10-16

>我有一个地图测试,它的初始化如下

test["auto  works"] = 1;
test["before word"] = 2;
test["before list"] = 3;
test["before pattern"] = 4;
test["before me"] = 5;
test["before hen"]  = 6;
test["has float"] = 7;

我有一个字符串搜索,初始化为"在我之前 grep lot"。

现在我想在测试地图中找到搜索字符串。理想情况下,我希望在测试地图中寻找更好的搜索字符串"在我之前 grep lot"。

输出应为 5。

请帮帮我。

使用test.lower_bound(search)(文档)。

尝试以下方法

#include <iostream>
#include <string>
#include <map>
#include <algorithm>
#include <iterator>

int main()
{
    std::map<std::string, int> test;
    test["auto  works"]    = 1;
    test["before word"]    = 2;
    test["before list"]    = 3;
    test["before pattern"] = 4;
    test["before me"]      = 5;
    test["before hen"]     = 6;
    test["has float"]      = 7;
    std::string s( "before me grep lot" );
    auto it = test.lower_bound( s );
    size_t prev = 0, next = 0;
    if ( it != test.begin() )
    {        
        auto pos = std::mismatch( s.begin(), s.end(),
                                  std::prev( it )->first.begin(), std::prev( it )->first.end() );
        prev = std::distance( s.begin(), pos.first );
    }       
    if ( it != test.end() )
    {
        auto pos = std::mismatch( s.begin(), s.end(),
                                  it->first.begin(), it->first.end() );
        prev = std::distance( s.begin(), pos.first );
    }       
    std::string target = prev < next ? it->first : std::prev( it )->first;
    std::cout << "The closest item is test["" << target << ""] = " << test[target] << std::endl;
}

程序输出为

The closest item is test["before me"] = 5

如果您的编译器标准库不支持算法 std::与四个参数不匹配,则 if 语句可能如下所示

if ( it != test.begin() )
{
    std::cout << std::prev( it )->first << std::endl;
    std::string::size_type n = std::min( s.size(), std::prev( it )->first.size() );
    auto pos = std::mismatch( s.begin(), std::next( s.begin(), n ),
                              std::prev( it )->first.begin() );
    prev = std::distance( s.begin(), pos.first );
}       
if ( it != test.end() )
{
    std::cout << it->first << std::endl;
    std::string::size_type n = std::min( s.size(), std::prev( it )->first.size() );
    auto pos = std::mismatch( s.begin(), std::next( s.begin(), n ),
                              it->first.begin() );
    prev = std::distance( s.begin(), pos.first );
}