Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/129.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 使用前插入器而不是后插入器_C++_Iterator_Std - Fatal编程技术网

C++ 使用前插入器而不是后插入器

C++ 使用前插入器而不是后插入器,c++,iterator,std,C++,Iterator,Std,伙计们! 我试图理解迭代器的工作,因此在下面的代码中,是否可以在不更改底层数据(结构)的情况下将back\u inserter更改为front\u inserter。 请你解释一下原因好吗。如果改变是可能的,考虑它的关键思想。 int a1[] = { 0, 1, 2, 3, 4, 5, 6 }; int a2[] = { 1, 4, 5 }; std::vector<int> a3; int a4[] = { 0, 2, 3, 6 }; std::set_difference(a1

伙计们! 我试图理解迭代器的工作,因此在下面的代码中,是否可以在不更改底层数据(结构)的情况下将back\u inserter更改为front\u inserter。 请你解释一下原因好吗。如果改变是可能的,考虑它的关键思想。
int a1[] = { 0, 1, 2, 3, 4, 5, 6 };
int a2[] = { 1, 4, 5 };
std::vector<int> a3;
int a4[] = { 0, 2, 3, 6 };
std::set_difference(a1, a1 + 7, a2, a2 + 3, std::back_inserter(a3));
assert(std::equal(a3.begin(), a3.end(), a4));
inta1[]={0,1,2,3,4,5,6};
int a2[]={1,4,5};
std::载体a3;
inta4[]={0,2,3,6};
std::设置_差异(a1,a1+7,a2,a2+3,std::背_插入器(a3));
断言(std::equal(a3.begin(),a3.end(),a4));

谢谢大家!

没有,但您需要的是一个插入器:

std::set_difference(a1, a1 + 7, a2, a2 + 3, std::inserter(a3, a3.begin()));

插入迭代器只是迭代器的一个实现,它使用标准机制将某些内容插入到集合中。对于
back\u inserter
,通过调用容器上的
push\u back()
方法完成插入。因此,为了使用
back\u inserter
,容器必须实现
push\u back()

同样地,使用
front\u inserter
集合必须实现
push\u front()
,这将
向量
。因此,您不能在
向量
上使用
前端插入器


list
deque
都实现了
push_front
,因此如果要使用其中一个而不是
向量
,则可以使用
front_inserter

不,这是不可能的。它需要一个支持
push_front
@AndyProwl极好的响应:)的容器。请参阅我的答案,了解如何使用std::inserter来解决您的问题。说得好,但请随意复制我的解决方案,以利用Ops原始问题的首选解决方案。尽管这相对效率较低。