2015-06-20 54 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。等一下我會展示如何使用舊的算法。 –