2017-06-15 72 views
0

我正在嘗試使用regex_match()作爲count_if()中的謂詞,其中vector<string>元素用於類成員函數中。但不知道如何正確繞過第二個參數(正則表達式值)到函數中。 是否有辦法使用regex_match()作爲謂詞(例如bind1st())?regex_match作爲謂詞

int GetWeight::countWeight(std::regex reg) 
{ 
std::cout << std::count_if(word.begin(),word.end(),std::bind1st(std::regex_match(),reg)) << std::endl; 
return 1; 
}; 

字 - 是我需要來算匹配std::regex reg元素繞過類的外部vector<std::string>

+0

如果簽名不匹配正好,你不能插上直接..雖然答案下面看起來不錯。 – xaxxon

回答

2

這裏有一個例子,你如何可以在std::count_if謂語使用Lambda做到這一點:

using Word = std::string; 
using WordList = std::vector<Word>; 

int countWeight(const WordList& list, const std::regex& reg) 
{ 
    int weight { 0 }; 

    weight = std::count_if(begin(list), end(list), [&reg](const Word& word) 
    { 
     std::smatch matches; 
     return std::regex_match(word, matches, reg); 
    }); 

    return weight; 
}; 
+0

我也[發現](https://stackoverflow.com/questions/15771434/counting-matches-in-vector-of-structs)使用函數作爲表達式的技巧。 –

+0

@Alex_H:好吧,使用lambda可以避免你自己編寫所有樣板代碼。 ;) – Azeem

+0

Ofc,但函數可以更便攜。謝謝,Azeem。 –