【问题标题】:regex_match as predicateregex_match 作为谓词
【发布时间】:2017-06-15 04:57:05
【问题描述】:

我正在尝试使用std::regex_match() 作为std::count_if() 中的谓词和类成员函数中的std::vector<string> 元素。但不知道如何才能正确地将第二个参数(正则表达式值)绕过到函数中。

有没有办法将std::regex_match() 用作谓词(例如std::bind1st())?

例子:

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

wordvector&lt;std::string&gt;,我需要计算匹配 std::regex reg 的元素绕过类外。

【问题讨论】:

  • 如果签名不完全匹配,你不能直接插入它。虽然下面的答案看起来不错。

标签: c++ regex c++11 predicate


【解决方案1】:

这是一个示例,您可以如何在 std::count_if 的谓词中使用 lambda:

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

int countWeight( const WordList& list, const std::regex& re )
{
    return std::count_if( list.cbegin(), list.cend(), [&re]( const Word& word )
    {
        std::smatch matches;
        return std::regex_match( word, matches, re );
    });
};

【讨论】:

  • 我也found 使用仿函数作为表达式的技巧。
  • @Alex_H:嗯,使用 lambda 可以避免您自己编写所有样板代码。 ;)
  • Ofc,但仿函数可以更便携。谢谢你,Azeem。
  • @Alex_H:不客气! :) 您能否详细说明仿函数与使用 lambda 的“可移植性”? AFAIK,作为语言的一部分的 lambda 与该语言的任何其他功能一样可移植。而且,与仿函数相比,使用 lambda 可以提供更好的“局部性”。它看起来更优雅,代码的编写和维护可以在同一个地方处理。相比之下,在代码审查和维护时,使用函子需要更多的编写和工作量。我非常感谢您对此的意见。提前致谢。 :)
  • 我的意思是不同的 C++ 标准。据我所知,lambda 存在于 C++11 中。我认为您可以满足需要支持的遗留代码。我完全同意你在代码中使用 lambda 的理由。此功能使开发更清洁、更轻松。
猜你喜欢
  • 2014-05-20
  • 1970-01-01
  • 2021-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-23
  • 1970-01-01
相关资源
最近更新 更多