【问题标题】:Does boost or STL have a predicate for comparing two char values?boost 或 STL 是否具有用于比较两个 char 值的谓词?
【发布时间】:2015-09-01 10:29:16
【问题描述】:

我需要在单个char 值上调用boost::trim_left_if

// pseudo code; not tested.
std::string to_trim{"hello"};
char left_char = 'h';
boost::algorithm::trim_left_if(to_trim, /*left_char?*/);

在上面的最后一行中,我需要一种方法来传递char 值。我环顾四周,但在 Boost 或 STL 中没有看到用于简单比较两个任意值的通用谓词。我可以为此使用 lambda,但如果存在谓词,我更喜欢谓词。

我想在这里避免的一件事是使用boost::is_any_of() 或任何其他需要将left_char 转换为字符串的谓词。

【问题讨论】:

  • 你不能使用 lambda 吗? [&](char c) { return c == left_char; }.
  • is_from_range(left_char, left_char)?
  • @T.C.范围不是半开的?
  • @Yakk 不符合documentation
  • @T.C.我有点明白为什么,但是嗯。

标签: c++ c++11 boost stl


【解决方案1】:

自 C++11 起,将相等性与固定值进行比较的惯用方法是使用带有 std::equal_to 的绑定表达式:

boost::algorithm::trim_left_if(to_trim,
    std::bind(std::equal_to<>{}, left_char, std::placeholders::_1));

这使用透明谓词std::equal_to&lt;void&gt;(C++14 起);在 C++11 中使用 std::equal_to&lt;char&gt;

在 C++11 之前(并且可能在 C++17 之前),您可以使用 std::bind1st 代替 std::bindstd::placeholders::_1

在 Boost 中,你也可以使用 boost::algorithm::is_any_of 和一个单一的范围;我发现boost::assign::list_of 效果很好:

boost::algorithm::trim_left_if(to_trim,
    boost::algorithm::is_any_of(boost::assign::list_of(left_char)));

【讨论】:

    【解决方案2】:

    为什么不写一个?

    #include <iostream>
    #include <boost/algorithm/string/trim.hpp>
    
    struct Pred
    {
        Pred(char ch) : ch_(ch) {}
        bool operator () ( char c ) const { return ch_ == c; }
        char ch_;
    };
    
    int main ()
    {
        std::string to_trim{"hello"};
        char left_char = 'h';
        boost::algorithm::trim_left_if(to_trim, Pred(left_char));
        std::cout << to_trim << std::endl;
    }
    

    说真的 - boost 中的东西不是“从天上降下来的”,而是像你我这样的人写的。

    【讨论】:

      猜你喜欢
      • 2011-08-30
      • 1970-01-01
      • 1970-01-01
      • 2019-09-19
      • 1970-01-01
      • 2013-06-09
      • 1970-01-01
      • 2012-02-11
      • 1970-01-01
      相关资源
      最近更新 更多