C++编写一个modify_if函数
我有一个硬件问题,这让我对我必须做什么感到困惑。问题如下:
- 这个想法是设计一个名为Modify_If的通用函数,它将接受输入x(通过引用传递)和两个函子f1和f2。函数Modify_If将使用函子f1来确定x是否满足某个条件。如果是这样,Modify_if 将通过应用函子 f2 来更改 x 的值。
修改_If 的原型如下:
template <class C, class Tester, class Transform>
void Modify_If(C & a, Tester f, Transform g)
我必须编写修改_If 函数,但我不知道从哪里开始,所以如果有人可以帮助我,我将不胜感激。
I have a hw question which confuses me on what i have to do. The question is below:
- The idea is to design a generic function called Modify_If that will take an input x (passed by reference), and two functors f1 and f2. The function Modify_If will use functor f1 to determine whether x obeys a certain condition. If it does, Modify_if will change the value of x, by applying functor f2 to it.
The prototype for Modify_If is as follows:
template <class C, class Tester, class Transform>
void Modify_If(C & a, Tester f, Transform g)
I have to write the Modify_If function but I have no idea where to start so if anyone can help me out I would appreciate it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
从描述来看,听起来您应该做的就是在
f(a)
返回 true 时执行g(a)
。那看起来像这样:From the description it sounds like all you're supposed to do is to execute
g(a)
iff(a)
returns true. That would look like this:函数原型可能如下所示:
在其实现中,您应该迭代所有元素集,并将
Func
应用于将为Pred(*element_iterator)
返回 true 的所有元素。Function prototype could look as follows:
In its implementation you should iterate through all set of elements and apply
Func
to all elements that will return true forPred(*element_iterator)
.在函子
Tester
和Transform
中,您所要做的就是为每个函子创建一个类,并重载()
运算符。然后像函数一样编写函子的主体。这是一个简单的函子骨架:然后,您可以通过创建函子的对象或轻松地动态创建它来将函子作为参数传递:
In both functors
Tester
andTransform
, all what you have to do is to create a class for each, and overload the()
operator. Then write the body of the functor as if it were a function. This is a simple functor skeleton:Then, you can pass the functor as a parameter, by creating an object of it, or easily by creating it on the fly: