繁体   English   中英

复制阵列并清理

[英]Copying Arrays and cleaning up

我正在尝试将阵列复制到更大的阵列中,然后删除旧的阵列进行清理。 该类具有一个int和一个指针,并重写析构函数以确保在可以delete []时不删除该指针。 但是我的delete []抛出了异常。 我用= new field[1000]; 初始化数组。

我收到"Collections.exe has triggered a breakpoint." ,但断点不是我的。

inline void _resize(unsigned int newTableSize, bool _trimCalled){ 
            if (newTableSize < tableSize && _trimCalled == false) {
                _trim();
                return; 
            }
            field* newTable = new field[newTableSize]; 
            for (unsigned int x = 0; x < newTableSize; x++)
                newTable[x] = table[x];
            tableSize = newTableSize;  
            delete[] table;
            table = newTable;   

    }
inline void _trim(){
    // compact the table 
    // fill in from the end of the table
    for (int x = tableSize; !emptyPlaces.empty() ; x--){
        if (table[x].used = true){
            table[emptyPlaces.top()] = table[x];
            emptyPlaces.pop();
        }
    }
    // trim the excess
    _resize((unsigned int)(usedFields * 1.1 + 10), true);


template<typename key, typename object> class DictonaryArray {
    struct field{
        field(){ this->key = 0; this->_object = nullptr; this->used = false; }
        field(key _key, object __object){;
            key = _key;
            _object = new object();
            *_object = __object;
            this->used = true;
        }
        ~field(){ 
        }
        key key;
        object* _object;
        bool used;
    };
table = newtable;; 
delete[] table;

看起来可疑。

也许你想要

delete[] table;
table = newTable; 

删除旧表并为其分配新表的地址。

编辑1:

另外,假设tableSize是旧表的大小

for (unsigned int x = 0; x < newTableSize; x++)

需要是

for (unsigned int x = 0; x < tableSize; x++)

因为table[x]只能读取到tableSize-1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM