迭代器和 back_insert_iterator 有什么区别? [英] What's the difference between iterator and back_insert_iterator?
问题描述
如果随机访问迭代器可用于访问相对于它们指向的元素的任意偏移位置的元素(某种程度上类似于指针),为什么它们不能用于像 std::copy() 这样的通用算法中
而不是使用 back_insert_iterator
,两者有什么区别?
If random access iterators can be used to access elements at an arbitrary offset position relative to element they point to (somehow like pointers), why can't they be used in generic algorithms like std::copy()
instead of using back_insert_iterator
, and what's the difference between both?
推荐答案
std::back_insert_iterator
是输出迭代器的特定种类支持push_back
操作.当您使用 operator=
写入时,它会将值推回底层容器中 —因此,从这个意义上说,它充当具有 push_back
成员函数的容器的适配器.
std::back_insert_iterator
is a specific kind of output iterator which supports push_back
operation. When you write to it using operator=
, it push_backs the value into the underlying container — so, in that sense it acts as an adaptor for containers which has push_back
member function.
举个简单易懂的例子:
std::vector<int> v;
std::back_insert_iterator<std::vector<int>> it(v);
*it = 10; // it is equivalent to v.push_back(10);
it = 99; // it is ALSO equivalent to v.push_back(99);
for (auto const & i : v)
std::cout << i << " " ; //10 99
它输出:
10 99
在线演示.
通常的迭代器操作++
和*
对it
没有影响.
The usual iterator operations ++
and *
on it
has no effect.
但是你很少直接使用它们(直到现在我从来没有直接使用过).您将它们与算法一起使用,例如 std::copy
在这种情况下,您还可以使用 std::back_inserter
function 返回一个类型的对象std::back_insert_iterator
.
But you rarely use them directly (I've never used it directly untill now). You use them with algorithms, such as std::copy
in which case you also use std::back_inserter
function which returns an object of type std::back_insert_iterator
.
//assuming dest is a container which supports push_back!
std::copy(src.begin(), src.end(), std::back_inserter(dest));
您还希望看到以下(适配器)迭代器:
You would also like to see the following (adaptor) iterators:
- std::front_insert_iteratorn 支持
push_front
操作 - std::insert_iterator 支持
insert
操作.
- std::front_insert_iteratorn supports
push_front
operation - std::insert_iterator supports
insert
operation.
因此根据容器,您选择适配器迭代器.
So depending on the container, you choose adaptor iterator.
请注意,它们都是输出迭代器.
Note that all of them are output iterator.
为什么不能在像 std::copy() 这样的通用算法中使用它们而不是使用 back_insert_iterator.
why can't they be used in generic algorithms like std::copy() instead of using back_insert_iterator.
当然,您可以在诸如 std::copy
之类的算法中使用随机访问迭代器(或任何 输出 迭代器)作为第三个参数,但这假设迭代器正在引用现有范围 —*it
和 ++it
为您传递的值定义了良好.您将它们传递给覆盖范围的现有元素,而 std::back_insert_iterator
向容器添加新元素.
Of course, you can use the random access iterators (or any output iterator) in algorithms like std::copy
, as third argument, but that assumes the iterator is referencing to existing range — *it
and ++it
are well-defined for the value you passed. You pass them to overwrite the existing elements of the range, whereas std::back_insert_iterator
adds new elements to the container.
希望有所帮助.
这篇关于迭代器和 back_insert_iterator 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!