最好的解決方案是使用STL functional library。通過從unary_function<SomeType, bool>
中推導出謂詞,您將可以使用not1
函數,該函數完全符合您的需要(即否定一元謂詞)。
這裏是你如何能做到這一點:
struct FindPredicate : public unary_function<SomeType, bool>
{
FindPredicate(const SomeType& t) : _t(t) {}
bool operator()(const SomeType& t) const {
return t == _t;
}
private:
const SomeType& _t;
};
bool AllSatisfy(std::vector<SomeType>& v, SomeType& valueToFind)
{
return find_if(v.begin(),
v.end(),
not1(FindPredicate(valueToFind))) == v.end();
}
如果你想推出自己的解決方案(這是,恕我直言,不是最好的選擇...),好了,你可以寫另一個謂詞是第一位的否定:
struct NotFindPredicate
{
NotFindPredicate(const SomeType& t) : _t(t) {
}
bool operator()(SomeType& t) {
return t != _t;
}
private:
const SomeType& _t;
};
bool AllSatisfy(std::vector<SomeType>& v) {
return find_if(v.begin(),
v.end(),
NotFindPredicate(valueToFind)) == v.end();
}
或者你可以做的更好,並編寫模板仿函數否定器,如:
template <class Functor>
struct Not
{
Not(Functor & f) : func(f) {}
template <typename ArgType>
bool operator()(ArgType & arg) { return ! func(arg); }
private:
Functor & func;
};
,你可以如下使用:
bool AllSatisfy(std::vector<SomeType>& v, SomeType& valueToFind)
{
FindPredicate f(valueToFind);
return find_if(v.begin(), v.end(), Not<FindPredicate>(f)) == v.end();
}
當然,後一種解決方案是更好,因爲你可以重複使用不結構與你希望每一個函子。
然後像SGI的人確實返回一個不對象,而無需指定它的類型,你可以添加一個墊片模板函數。 –
xtofl
2008-11-05 19:55:17