【发布时间】:2021-07-11 20:13:30
【问题描述】:
我在一个类中有一个私有数组,动态分配。随着我插入越来越多的项目,我需要在某个时候调整数组的大小。问题是如何正确地做到这一点?下面的代码以错误结尾:munmap_chunk(): invalid pointer while inserting a third item.
#include <string>
#include <cstring>
#include <cassert>
using namespace std;
template<typename T>
class Set
{
private:
T * array;
size_t arraySize;
unsigned int itemCount;
public:
Set() {
arraySize = 1;
itemCount = 0;
array = new T[arraySize];
};
bool Insert(const T item) {
if (itemCount == arraySize) {
T * tmpArray = new T[arraySize * 2];
memcpy(tmpArray, array, arraySize * sizeof(T));
arraySize *= 2;
delete [] array;
array = tmpArray;
}
array[itemCount] = item;
itemCount++;
return true;
}
};
int main ()
{
Set<string> x0;
assert( x0 . Insert( "apple" ) );
assert( x0 . Insert( "orange" ) );
assert( x0 . Insert( "pineapple" ) );
return 0;
}
我知道我可以使用例如向量来不关心分配,但我想知道如何以这种方式正确地做到这一点。
如果问题不恰当,请见谅。这是我第一次提问
【问题讨论】:
-
memcpy仅适用于可简单复制的类型;你应该逐个元素地复制。 -
这是一种练习,还是您想要开箱即用的东西?
std::vector<T>可能就是你要找的。span> -
好的,绝对避免
memcpy。不要忘记析构函数。 -
@TedLyngmo 是的,我想避免使用 STL 容器。
-
@MatG 是的,避免
memcpy解决了问题:-)
标签: c++ class resize allocation