C++:查找并删除重复元素

问题

查找容器中的重复元素,并删除它们.

C++.
image-2094

源代码

问题2

你认为算法不改变容器大小的原因是什么?

解答

以下回答来自网络:

没有问题啊,Lippman前面自己不已经给出这个问题的答案了吗?

Key Concept: Algorithms Never Execute Container Operations
The generic algorithms do not themselves execute container operations. They operate solely in terms of iterators and iterator operations. The fact that the algorithms operate in terms of iterators and not container operations has a perhaps surprising but essential implication: When used on “ordinary” iterators, algorithms never change the size of the underlying container. As we’ll see, algorithms may change the values of the elements stored in the container, and they may move elements around within the container. They do not, however, ever add or remove elements directly.

As we’ll see in Section 11.3.1 (p. 406), there is a special class of iterator, the inserters, that do more than traverse the sequence to which they are bound. When we assign to these iterators, they execute insert operations on the underlying container. When an algorithm operates on one of these iterators, the iterator may have the effect of adding elements to the container. The algorithm itself, however, never does so.


fill_n(back_inserter(vec),10,0);
中,问题在于,fill_n算法从来都不会改变容器的size,改变容器size的是back_inserter,back_inserter并不是一种“算法”,它可以看成是种“迭代适配器”。
于是,上面这条语句中的fill_n是一直是在“被back_inserter修改着的”容器中插入无素,它本身从来不曾修改vec容器的大小,而且也不知道容器是否被谁改过。
换句话说,它只会低着头不断往里插,却不曾知道back_inserter一直在背地里协助它,并为之承担了“修改容器大小”的骂名,呵呵。
[原文]

发表评论

电子邮件地址不会被公开。 必填项已用*标注

*

评论审核已启用。您的评论可能需要一段时间后才能被显示。

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据