2017-06-15 232 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。 –