2015-06-20 53 views
-1

部分字符串匹配我有地图测试和初始化以下要查找地图

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很多”这样的字符串搜索。

现在我想在测试图中找到搜索字符串。理想情况下,我希望在测试地图中为搜索字符串“before grep lot”寻找更好的匹配。

输出应该是5.

请帮我一把。

+1

为什么'5'是“更好的匹配”? –

+0

是否要返回*全部*以搜索字符串开头的键? – Galik

回答

1

试试下面的办法

#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); 
}  
+0

非常感谢。但是当我编译,我得到以下错误: –

+0

sample.cpp(165):错误C2064:术语不计算为一个函数取1个参数 sample.cpp(165):错误C2227:' - >第一'指向类/结构/联合/泛型 sample.cpp(165):错误C2228:'.begin'的左侧必须具有类/结构/联合 sample.cpp(166):错误C2064:term不计算为函数取1个参数 1> sample.cpp(166):error C2227:' - > first'的左边必须指向class/struct/union/generic类型 sample.cpp(166):error C2228:left' .end'必须有类/结构/联合 std :: mismatch(_InIt1,_InIt1,_InTy(&)[_InSize])':期望3个参数 - 提供4个 –

+0

@S Sriniamul看起来你有一个旧的库不支持算法std ::与四个参数不匹配ERS。等一下我会展示如何使用旧的算法。 –