更新时间:2023-11-28 10:33:34
STL不提供这样的迭代器。但你可以自己编写代码(测试代码):
The STL does not provide such an iterator. But you could code it yourself (tested that code):
struct null_output_iterator :
std::iterator< std::output_iterator_tag,
null_output_iterator > {
/* no-op assignment */
template<typename T>
void operator=(T const&) { }
null_output_iterator & operator++() {
return *this;
}
null_output_iterator operator++(int) {
return *this;
}
null_output_iterator & operator*() { return *this; }
};
使用自身作为运算符的结果不需要任何数据*
。在输出迭代器的要求中不使用 * it = x;
的结果,所以我们可以给它一个返回类型 void
。
It doesn't need any data by using itself as the result of operator*
. The result of *it = x;
is not used in the output iterator requirements, so we can give it a return type of void
.
编辑:让我们进入运算符*
工程。标准在 24.1.2 / 1 中说明了在这两种情况下输出迭代器的要求:
Let's go into how this operator*
works. The Standard says in 24.1.2/1 about the requirements of an output iterator that in both these cases:
*it = t;
*it++ = t;
不使用这些表达式的结果。这是什么使这项工作:
That the result of those expressions is not used. That's what makes this work:
null_output_iterator it;
*it; // returns a null_output_iterator& per definition of the `operator*`.
*it = some_value; // returns void per definition of the templated `operator=`.
现在我们不需要在运算符中返回任何数据*
:我们只是使用迭代器本身。请注意,模板化运算符=不覆盖内置拷贝分配运算符。仍然提供。
Now we don't need to have any data that we return in operator*
: We just use the iterator itself. Note that the templated operator= does not overwrite the builtin copy assignment operator. It's still provided.