gpt4 book ai didi

c++ - std::unique 类对象

转载 作者:行者123 更新时间:2023-11-28 01:57:43 34 4
gpt4 key购买 nike

有一个带有指向类对象指针的双端队列:

deque<myClass*> mydeque;

假设我们在双端队列中有 3 个对象:obj1、obj2、obj3

根据一些比较逻辑,obj1obj2 被认为是相同的元素。

当我们在 mydeque 上调用 std::unique 时,它会将双端队列更改为如下所示:

obj1 obj3 obj3

这是因为根据 std::unique 的文档 删除是通过用下一个不是重复的元素替换重复元素来完成的

std::unique 返回指向最后一个 obj3 的迭代器。如果我们想释放obj2占用的内存空间(通过调用delete),我们如何实现?

这里我们不能对返回的迭代器调用 delete,因为它实际上会删除 obj3。

最佳答案

这是 std::unique 的文档说:

Removing is done by shifting the elements in the range in such a way that elements to be erased are overwritten. Relative order of the elements that remain is preserved and the physical size of the container is unchanged.

Iterators pointing to an element between the new logical end and the physical end of the range are still dereferenceable, but the elements themselves have unspecified values.

A call to unique is typically followed by a call to a container's erase method, which erases the unspecified values and reduces the physical size of the container to match its new logical size.

注意 2 个粗体部分。第一个很重要,它表示相对顺序被保留,即在调用 std::unique 之后,你的双端队列仍将包含

obj1 obj2 obj3

他们的顺序没有改变,为什么?因为非唯一元素已经在末尾,obj3,并且因为保留了顺序,所以您可以确定它仍会在末尾。

第二个粗体部分你已经知道了,但现在你知道 std::unique 返回一个指向最后一个有效元素的迭代器,你可以调用 std::deque::erase删除每个非唯一元素:

mydeque.erase(std::unique(mydeque.begin(), mydeque.end()), mydeque.end());

另请注意,因为您正在存储指针,所以拥有 2 个相同元素的唯一方法是让 2 个指针指向同一地址。

关于c++ - std::unique 类对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40593861/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com