stable_sort包含动态表的对象

stable_sort on objects containing dynamic tables

本文关键字:对象 动态 包含 sort stable      更新时间:2023-10-16

我在排序方面有问题。我对包含动态表的对象进行排序。似乎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;
 }