[英]How to compose functors with STL?
STL中可能有以下內容:
int count = count_if(v.begin(), v.end(), bind2nd(less<int>(), 3));
這將返回v中小於3的元素數。如何組成一個返回0到3之間元素數的仿函數? 我知道boost有一些設施,但純STL有可能嗎?
如果你的意思是使用標准庫的functor組合工具,那么不,至少在C ++ 98中沒有。 在C ++ 11中,您可以將std::bind
用於任意組合的仿函數:
using std::placeholders;
int count = std::count_if(v.begin(), v.end(),
std::bind(std::logical_and<bool>(),
std::bind(std::less<int>(), _1, 3),
std::bind(std::greater<int>(), _1, 0)));
但對於這樣一個簡單的謂詞來說,這並沒有真正令人頭痛。
如果允許C ++ 11特性,那么最簡單的方法可能是lambda,不需要復制仿函數組合(你自己):
int count = std::count_if(v.begin(), v.end(), [](int arg) {
return arg > 0 && arg < 3; });
但對於C ++ 98, Chubsdad的答案可能是最好的解決方案。
這是你問的問題嗎? 我知道這不是純粹的STL,但仍然......
struct InRange
{
InRange(int x, int y) : mx(x), my(y) { }
bool operator()(int x)
{
return (x >= mx) && (x <= my);
}
int mx, my;
};
int main() {
std::vector<int> v;
v.push_back(13);
v.push_back(14);
v.push_back(18);
v.push_back(3);
int count = std::count_if(v.begin(), v.end(), InRange(0, 3));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.