2015-06-16 35 views
1

我需要调用boost::trim_left_if在单一char值:boost或STL是否有一个用于比较两个char值的谓词?

// 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转换为字符串的谓词。

+1

难道你不能使用lambda? '[&](char c){return c == left_char; }'。 – refi64

+1

'is_from_range(left_char,left_char)'? –

+0

@ T.C。范围不是半开放的? – Yakk

回答

2

由于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<void>(因为C++ 14 );在C++ 11中使用std::equal_to<char>

在使用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))); 
0

为什么不写一个呢?

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

说真的 - 在提升中的东西不是“从高处发送”,它是由你和我这样的人写的。