stable_sort包含动态表的对象
stable_sort on objects containing dynamic tables
我在排序方面有问题。我对包含动态表的对象进行排序。似乎stable_sort(或向量(不使用公共复制构造函数。我看起来他们使用了一个不存在的没有参数的构造函数,因为对象中的表被释放了 - 我认为。
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
class Dynamic{
int n;
int *tab;
public:
int getN() const{ return n;}
int *getTab() const {return tab;}
Dynamic(int ile){
n=ile;
tab=new int[n];
for(int i=0; i<n; i++)
tab[i] = (10-i)%10;
}
Dynamic(const Dynamic& d){
n = d.getN();
tab = new int[n];
for(int i=0; i<n; i++)
tab[i] = d.getTab()[i];
}
bool operator<(const Dynamic& a) const{
return n < a.getN();
}
~Dynamic(){
delete[] tab;
}
};
int test(vector<Dynamic> & c){
vector<Dynamic> d(c);
stable_sort(d.begin(), d.end());
d.clear();
}
int main(){
vector<Dynamic> c;
c.push_back(Dynamic(15));
test(c);
cout<<"test!";
return 0;
}
STL的排序也受到影响,但方式稍微复杂一些。在 g++-4.7.2 中,我可以编译它,在运行时我得到"双重释放或损坏(快速顶部("/核心转储(我认为完整报告没有帮助(。在在线 g++-4.9.0 上,它看起来类似:"无输出:错误:标准输出 maxBuffer 超出。
我的错误在哪里?感谢您的关注。
好吧,您没有为Dynamic
重载operator=
,因此编译器隐式定义了一个将执行按位复制的编译器。 库中stable_sort()
调用operator=
,因此tab
两个Dynamic
对象指向同一地址,因此,销毁时会重复删除。重载operator=
将解决问题:
Dynamic& operator =(const Dynamic& d)
{
// or use the copy-and-swap idiom
if(this != &d)
{
delete [] tab;
n = d.getN();
tab = new int[n];
for (int i = 0; i<n; i++)
tab[i] = d.getTab()[i];
}
return *this;
}
相关文章:
- C++中的动态对象与非动态对象
- 对具有动态分配的内存和析构函数的类对象的引用
- 我有一个对象,它将在整个程序的持续时间内实例化,但一个类成员不会,我应该动态分配它吗?
- 在对象指针上调用 Delete 是否会递归删除其动态分配的成员
- 生成文件:动态源文件名和对象目录
- 我们可以通过 IPC 传递具有动态管理成员的类对象吗?
- 使用动态实例化的对象填充矢量的快速方法
- 如何在 Cheerp/js 中迭代动态命名的对象?
- 销毁C++中动态分配的内存(数组对象)
- 创建动态对象并将其推送到矢量中
- 删除包含包含动态对象的 STL 容器的智能指针
- C++ 将抽象类型的动态分配对象传递给函数并存储在向量中
- 如何在运行时在对象数组中动态追加新对象C++并打印它们
- 将基类分配给派生对象,反之亦然,以C++以及静态和动态对象之间的差异
- 如何访问对象动态数组中的私有成员变量?
- 如果您为类的一个对象动态分配内存作为参数,会发生什么
- Cython 中对象动态大小的数组
- malloc分配的对象动态类型是什么
- C++按属性排序的对象动态数组
- visual C++新与Malloc的对象动态内存阵列