简体   繁体   English

boost或STL是否具有比较两个char值的谓词?

[英]Does boost or STL have a predicate for comparing two char values?

I need to call boost::trim_left_if on a single char value: 我需要在单个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?*/);

In the last line above, I need a way to pass in the char value. 在上面的最后一行中,我需要一种传递char值的方法。 I looked around but I didn't see a generic predicate in Boost or STL to simply compare two arbitrary values. 我环顾四周,但没有看到Boost或STL中的泛型谓词可以简单地比较两个任意值。 I could use lambdas for this but would prefer the predicate, if one exists. 我可以为此使用lambda,但如果存在谓词,则更喜欢谓词。

One thing I want to avoid here is using boost::is_any_of() or any other predicates that would require left_char to be converted to a string. 我要避免的一件事是使用boost::is_any_of()或需要将left_char转换为字符串的任何其他谓词。

Since C++11, the idiomatic way to compare for equality to a fixed value is to use a bind-expression with std::equal_to : 从C ++ 11开始,将相等性与固定值进行比较的惯用方式是对std::equal_to使用bind-expression:

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

This uses the transparent predicate std::equal_to<void> (since C++14); 这使用了透明谓词std::equal_to<void> (自C ++ 14起); in C++11 use std::equal_to<char> . 在C ++ 11中使用std::equal_to<char>

Prior to C++11 (and, likely, until C++17) you can use std::bind1st in place of std::bind and std::placeholders::_1 . 在C ++ 11之前(可能直到C ++ 17),您可以使用std::bind1st代替std::bindstd::placeholders::_1

Remaining within Boost, you could also use boost::algorithm::is_any_of with a unitary range; 在Boost中,您还可以使用boost::algorithm::is_any_of单位范围; I find boost::assign::list_of works well: 我发现boost::assign::list_of效果很好:

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

Why not just write one? 为什么不只写一个?

#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;
}

Seriously - the stuff in boost is not "sent down from on high", it's written by people like you and me. 认真地讲,助推的东西并不是“从高处寄”,它是由像你我这样的人写的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM