【问题标题】:stable_sort on objects containing dynamic tables对包含动态表的对象进行 stable_sort
【发布时间】:2014-04-23 08:35:44
【问题描述】:

我的排序有问题。我对包含动态表的对象进行排序。似乎 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 中,我可以编译它并在运行时得到“双重释放或损坏(fasttop)”/核心转储(我认为完整报告没有帮助)。在在线 g++-4.9.0 上看起来类似:“No output: Error: stdout maxBuffer exceeded.”。

我的错误在哪里?感谢您的关注。

【问题讨论】:

  • 查找三的规则,尤其是 op=
  • 感谢您的好建议!

标签: c++ sorting vector stl stable-sort


【解决方案1】:

好吧,你没有为Dynamic 重载operator=,所以编译器隐含地定义了一个可以按位复制的。库中的stable_sort() 调用了operator=,因此两个Dynamic 对象中的tab 指向相同的地址,因此,在销毁时双重删除。重载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;
 }

【讨论】:

    猜你喜欢
    • 2018-02-12
    • 1970-01-01
    • 2015-08-24
    • 1970-01-01
    • 1970-01-01
    • 2013-04-29
    • 2015-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多