drb*_*rby 7 c++ functional-programming stl predicate
有没有什么方法可以组合谓词?
让我们说我有这样的事情:
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;
}
Run Code Online (Sandbox Code Playgroud)
这有效,但现在我想做一些事情:
searchResult = find_if(tokens.begin(), tokens.end(), bind2nd(MatchBeginning(), "-b") || not1(bind2nd(MatchBeginning(), "-")));
Run Code Online (Sandbox Code Playgroud)
所以我想找到第一个以"-b"开头的字符串或第一个不以" - "开头的字符串.但是,这给了我一个错误(二进制'||'未定义).
有没有办法做到这一点?
我可以推荐boost.lambda来组合这些任务的函数对象.虽然这样一个简单的问题有点重量级.(编辑)查看xhantt发布的社区wiki答案,以获取使用STL的一个好例子.
(旧的,不推荐的,回答)您可以为此编写自己的实用程序,类似于:
// 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);
}
Run Code Online (Sandbox Code Playgroud)
然后使用它: ... lazy_or(bind1st(...), bind1st(...)) ...
那么你有std :: logical_or和std :: compose2可以完成这项工作
find_if(tokens.begin(), tokens.end(),
compose2(logical_or<bool>(),
bind2nd(MatchBeginning(), "-b"),
bind2nd(MatchBeginning(), "-")
)
);
Run Code Online (Sandbox Code Playgroud)
但我认为boost :: lambda和/或phoenix最后更具可读性,是我推荐的解决方案.
积分应该转到SGI文档.