C 插入UNOREREDED_SET中会打破我的程序

C++ inserting into an unordered_set breaks my program

本文关键字:我的 程序 插入 UNOREREDED SET      更新时间:2023-10-16

我为unordered_set创建了一个自定义类和自定义哈希函数。每当我尝试将其插入该unordered_set时,我都会收到一个内存错误:

malloc: *** error for object 0x9000000000000000: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
Abort trap: 6

我必须使用unordered_set。

这是我的自定义类:

template <class T>
class Seed {
  private:
    Point start;
    int seed_size;
    T** data;
    Seed* seed_match;
    T _value;
  public:
    Seed(int x, int y, int s): seed_size(s), data( new T*[s] ), _value( T() ) {
      start = Point(x, y);
      for ( int i = 0; i < seed_size; i++ )
          data[i] = new T[seed_size];
      for ( int i = 0; i < seed_size; i++ ) {
        for ( int j = 0; j < seed_size; j++ ) data[i][j] = NULL;
      }
      seed_match = NULL;
    }
    ~Seed() {
        for ( int x = 0; x < seed_size; x++ ) {
            delete [] data[x];
        }
      delete [] data;
    }
    void add(int x, int y, T color_val) {
      assert( data[x][y] == NULL );
      data[x][y] = color_val;
      _value += color_val;
    }
    bool match ( const Seed &_match ) {
      if ( seed_match == NULL ) {
        seed_match = &_match;
        return true;
      }
      else return false;
    }
    T get_color(int x, int y) const {
      assert( x >= 0 );
      assert( y >= 0 );
      assert( x < seed_size );
      assert( y < seed_size );
      return data[x][y];
    }
    bool operator==( const Seed<T> &b ) {
      for ( int x = 0; x < seed_size; x++ ) {
        for ( int y = 0; y < seed_size; y++ ) {
          if ( get_color(x, y) != b.get_color(x, y) ) return false;
        }
      }
      return true;
    }
    int seed_value() const { return _value; }
};

这些是我的自定义哈希功能:

template <class T>
struct SeedEqualByValue {
public:
    bool operator()(const Seed<T> & seed1, const Seed<T> & seed2) const {
        if (seed1.seed_value() == seed2.seed_value())
            return true;
        else
            return false;
    }
};
template <class T>
struct SeedHashByValue {
public:
    size_t operator()(const Seed<T> & s1) const {
        return std::hash<int>()( s1.seed_value() );
    }
};

在我的主体中,我将种子类的3个实例化成3个变量,并实例化了一个unordered_set,它将带有种子,哈希功能作为我的SeedhashbyValue struct,并将其比较为seedequalbyvalue struct。创建unordered_map后,每当我将种子对象插入unordered_map时,我会收到一个malloc错误,我不确定如何解决此问题。

这些是我的主要功能的内容:

Seed<int> b(0, 0, 5);
Seed<int> a(0, 0, 5);
Seed<int> c(0, 0, 5);
c.add(4, 4, 100);
a.add(1, 2, 4);
a.add(1, 1, 3);
b.add(1, 1, 3);
unordered_set<Seed<int>, SeedHashByValue<int>, SeedEqualByValue<int> > seeds;
seeds.insert(c); 

此外,Point只是一个具有公共成员变量int xint y的X和Y值的类,以防任何人需要澄清。

跟进@algirdas所说的话,我相信正在发生的事情是 Seed被浅入了集合,因此您最终在同一父母指针上获得了双delete,一次,当该设置范围内范围内,一次变量范围范围。

您需要通过在分配运营商中或使用诸如std::unique_ptr之类的内容并确保将其分配(默认情况下所有权)来修改如何处理数据。

相关文章: