有幾種方法可以爲算法提供謂詞。下面你會看到一些如何做到這一點的例子。這裏的呼叫的總結std::max_element()
:
//here we're using an in-place lambda
A& max_elem = *std::max_element(vec.begin(), vec.end(), [](A& x, A&y){ return x.f() < y.f(); });
// here we're binding to a non-static member function
A& max_elem = *std::max_element(vec.begin(), vec.end(), std::bind(&A::compare, A(0), std::placeholders::_1, std::placeholders::_2));
// here we're binding to a non-member function
A& max_elem = *std::max_element(vec.begin(), vec.end(), std::bind(gcompare, std::placeholders::_1, std::placeholders::_2));
// here we're using the non-member function without using bind
A& max_elem = *std::max_element(vec.begin(), vec.end(), gcompare);
我們也可以使用std::function
。
下面是完整的測試源代碼,以便您可以自己玩它:
class A
{
int m_ = 0;
public:
A(int max) : m_(max)
{
}
A(const A& that)
{
m_ = that.m_;
}
A& operator=(const A& that)
{
m_ = that.m_;
}
int f() const
{
return m_;
}
bool compare(const A&x, const A&y) const
{
return x.m_ < y.m_;
}
static bool scompare(const A&x, const A&y)
{
return x.m_ < y.m_;
}
};
static bool gcompare(const A&x, const A&y)
{
return x.f() < y.f();
}
int main()
{
std::vector<A> vec;
vec.emplace_back(5);
vec.emplace_back(7);
vec.emplace_back(4);
vec.emplace_back(9);
vec.emplace_back(12);
vec.emplace_back(1);
A& max_elem = *std::max_element(vec.begin(), vec.end(), [](A& x, A&y){ return x.f() < y.f(); });
A& max_elem = *std::max_element(vec.begin(), vec.end(), std::bind(&A::compare, A(0), std::placeholders::_1, std::placeholders::_2));
A& max_elem = *std::max_element(vec.begin(), vec.end(), std::bind(gcompare, std::placeholders::_1, std::placeholders::_2));
A& max_elem = *std::max_element(vec.begin(), vec.end(), gcompare);
}
既然你對你的決定哪個'的F()'應該是你比較基地隨意選擇的,我看不出有什麼希望這樣做*沒有*一些*類型的自定義比較器(無論是函子還是lambda,而我的錢在前者用於指向成員的便利)。或者......我完全不理解這個問題(它的2點半在這裏,現在真的應該在牀上)。 – WhozCraig
查看['std :: bind'](http://en.cppreference.com/w/cpp/utility/functional/bind),['std :: placeholders :: _ 1'](http:// en .cppreference.com/w/cpp/utility/functional /佔位符)和相關。 – Angew
當我說「沒有從頭開始定義我自己的比較器」時,我的意思是我想從'less <>'和其他構建塊(比如'bind')這樣的東西放在一起,最終會調用'f() '。我已經看過「綁定」和「佔位符」,但無法弄清楚如何處理這些問題。 – Ari