【发布时间】:2023-03-06 03:15:01
【问题描述】:
我们被教导创建函数对象以使用算法。
有算法调用operator(),比如:
- for_each
- find_if
- remove_if
- 最大元素
- count_if
这些函数对象通常应该从unary_function 或binary_function 继承,以表现得像函数、谓词等。
但书籍通常不会展示创建OutputIterators 的示例:
例如遍历函数的输出,如
std::set_intersection(),我要提供一个目的容器,
然后遍历结果:
std::vector<int> tmp_dest;
std::set_difference (
src1.begin(), src1.end(),
src2.begin(), src2.end(),
std::back_inserter(tmp_dest));
std::for_each( tmp_dest.begin(), tmp_dest.end(), do_something );
int res = std::accumulate( tmp_dest.begin(), tmp_dest.end(), 0 );
但认为有时使用每个算法的值而不先存储它们会更有效,例如:
std::set_difference (
src1.begin(), src1.end(),
src2.begin(), src2.end(),
do_something );
Accumulator accumulate(0); // inherits from std::insert_iterator ?
std::set_difference (
src1.begin(), src1.end(),
src2.begin(), src2.end(),
accumulate );
- 我们一般应该创建像这样的类 Accumulator 吗?
- 它的设计应该是什么样的?
- 它应该继承什么?
Accumulator 可以继承自
insert_iterator,但它并不是真正的迭代器(例如,它没有实现operator++())
被广泛接受的做法是什么?
【问题讨论】:
-
我会说这很好,但不要从
insert_iterator继承,它不是 插入迭代器,它是消耗数据的输出迭代器。 -
在算法列表中
std::for_each()与其他算法不同:其他算法使用谓词,std::for_each()使用消费者。 -
@Dietmar:实际上,很多时候,
find_if被使用而不是for_each,并且您将 谓词 用作 consumer,但是您还具有尽早中断迭代的优势。所以,真的,它们都是一样的。 -
@GrimFandango:虽然谓词可以像消费者一样使用,但实际上并不要求每次调用同一个副本。如果假设谓词是消费者,请确保对象的消费者部分具有引用语义。对于
std::for_each(),需要移动函数对象(如果它是可移动的),即,该对象不会被复制并且可以直接作为消费者工作。我认为这些函数对象之间是的。