我们被教导创建函数对象以使用算法。
有调用operator()
的算法,比如:
- for_each
- find_if
- remove_if
- 最大元素
- count_if
这些函数对象通常应该从 unary_function
或 binary_function
继承,以表现得像 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++()
)
被广泛接受的做法是什么?
最佳答案
如果您想要一个输出迭代器,它为收到的每个值调用您自己的函数,请使用 Boost.Iterator's function_output_iterator .
关于c++ - 伪造插入器是一种好习惯吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18897123/