在运行时指定多个谓词
STL中有一些运算符类,如less、equal_to、greater_equal等。如何轻松地将它们组合起来与remove_if函数一起使用?
例如我想删除向量中大于0且小于3且不等于2的元素,那么它会是这样的:
remove_if (v.begin(), v.end(), bind2nd(greater<int>(),0) + bind2nd(less<int>(),3) + not1(bind2nd(equal_to<int>(), 2)));
用户在程序运行期间可以指定过滤选项,例如他可以写:remove if x > ; 0 && x < 3&& x != 2,或者他可以写:如果 x > 则删除5 || x == 3。然后解析命令,并将适当的运算符及其参数组合在一起形成一个谓词。
There are operator classes in STL like less, equal_to, greater_equal etc. How to easily combine them to use with for example remove_if function?
For example I want to remove in vector elements which are greater than 0 AND less than 3 AND not equal to 2, then it would be something like:
remove_if (v.begin(), v.end(), bind2nd(greater<int>(),0) + bind2nd(less<int>(),3) + not1(bind2nd(equal_to<int>(), 2)));
User during running of program can specify filtering options for example he can write: remove if x > 0 && x < 3 && x != 2, or he can write: remove if x > 5 || x == 3. Then command is parsed and appropriate operators with their arguments are combined together to one predicate.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
实际上,对于您的情况来说,这相当简单。
首先需要解析用户给出的语句,并将其转化为AST(抽象语法树)。事实证明,这个 AST 几乎已经合适了。
可以表示为树:
所有节点都应该继承自一个公共基类,并且您应该实现一个
Visitor
来评估x
参数的给定值。This is rather simple in your case, actually.
You first need to parse the statement the user gave, and turn it into an AST (Abstract Syntax Tree). It turns out that this AST is nearly already suitable.
Can be expressed as a tree:
All nodes should inherit from a common base class, and you should implement a
Visitor
to evaluate thex
parameter for a given value.我猜你所说的“动态组合”是指“内联”“组成”谓词的能力。在您的示例中,谓词在编译时已知,因此“动态”不是正确的术语。
考虑“Boost.Bind”。它为组合提供运算符重载。
编辑:
考虑到您对“动态组合”的解释,上面的代码不是您想要的。您需要一个表达式解析器和评估器。但这与您的实际代码示例关系不大。对此没有简单的解决方案。您可以尝试检查一些表达式解析器库,看看它们是否/哪些适合您的问题。
I guess by "dynamic combining" you refer to the ability to "compose" the predicate "in-line". In your example, the predicate is known at compile-time, so, "dynamic" is not the right term for that.
Consider "Boost.Bind". It offers operator overloading for composition.
Edit:
Cosidering your explanation of "dynamic composition", the above code is not what you want. You need an expression parser and evaluator. But this has little to do with your actual code example. There is no easy solution to this. You could try to check out some expression parser libraries and see if / which of them are suitable for your problem.