组合谓词 [英] Combining Predicates
问题描述
有什么办法可以组合谓词吗?
Is there any way that you can combine predicates?
假设我有这样的:
class MatchBeginning : public binary_function<CStdString, CStdString, bool>
{ public:
bool operator()(const CStdString &inputOne, const CStdString &inputTwo) const
{ return inputOne.substr(0, inputTwo.length()).compare(inputTwo) == 0; }
};
int main(int argc, char* argv[])
{
CStdString myString("foo -b ar -t az");
vector<CStdString> tokens;
// splits the string every time it encounters a "-"
split(myString, tokens, "-", true, true);
vector<CStdString>::iterator searchResult = find_if(tokens.begin(), tokens.end(), not1(bind2nd(MatchBeginning(), "-")));
return 0;
}
这样可以工作,但现在我想做一些像: p>
This works, but now I'd like to do something like:
searchResult = find_if(tokens.begin(), tokens.end(), bind2nd(MatchBeginning(), "-b") || not1(bind2nd(MatchBeginning(), "-")));
所以我想找到以-b开头的第一个字符串或第一个字符串不以 - 开头。但是,这给我一个错误(二进制'||'未定义)。
So I'd like to find the first string that starts with "-b" or the first string that does not start with "-". However, this gives me an error (binary '||' undefined).
有任何方法吗?
推荐答案
推荐boost.lambda组合这些任务的函数对象。虽然这是一个有点重量这样一个简单的问题。 (编辑)使用STL查看xhantt开始的社区Wiki答案。
I can recommend boost.lambda for combining function-objects for such tasks. Although it is a bit heavyweight for such a simple problem. (edit) See the community wiki answer started by xhantt for a good example using STL.
(old,deprecated,answer)你自己的实用程序为此,类似:
(old, deprecated, answer) You can write your own utility for this, similar:
// here we define the combiner...
template<class Left, class Right>
class lazy_or_impl {
Left m_left;
Right m_right;
public:
lazy_or_impl(Left const& left, Right const& right) : m_left(left), m_right(right) {}
typename Left::result_type operator()(typename Left::argument_type const& a) const {
return m_left(a) || m_right(a);
}
};
// and a helper function which deduces the template arguments
// (thx to xtofl to point this out)
template<class Left, class Right>
lazy_or_impl<Left, Right> lazy_or(Left const& left, Right const& right) {
return lazy_or_impl<Left, Right>(left, right);
}
然后使用它: ... lazy_or bind1st(...),bind1st(...))...
这篇关于组合谓词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!