2015-06-16 37 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; 
} 

說真的 - 在提升中的東西不是「從高處發送」,它是由你和我這樣的人寫的。