2013-06-04 27 views
0

伙计! 我想了解迭代器的工作,所以在下面的代码中,是否可以将back_inserter更改为front_inserter而不更改基础数据(结构)。 请你解释一下为什么。如果改变是可能的考虑它的关键想法。使用front_inserter而不是back_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)); 

谢谢大家!

+3

你试过了吗? –

+4

不,这是不可能的。它需要一个支持'push_front'的容器。 – juanchopanza

+0

@AndyProwl出色的响应:) –

回答

0

没有,但你想要的是一个插入:

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

虽然这是相对低效的。 –

4

的插入迭代仅仅是其中插入一些在使用标准机制集合的迭代器的实现。在back_inserter的情况下,插入通过调用容器上的push_back()方法完成。因此,为了使用back_inserter,容器必须实现push_back()

同样,与front_inserter收集器实施push_front(),其中vectordoes not。因此,您不能在vector上使用front_inserter

listdeque都实现push_front,所以如果你使用其中的一个,而不是一个vector,你可以使用front_inserter

+0

好吧,但随时可以复制我的解决方案,以利用Ops原始问题的首选解决方案。 – TimeHorse