[英]How to resize a dynamically allocated array inside a class?
我在 class 中有一个私有数组,动态分配。 随着我插入越来越多的项目,我需要在某个时候调整数组的大小。 问题是如何正确地做到这一点? 下面的代码以错误结尾: 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;
}
我知道我可以使用例如向量来不关心分配,但我想知道如何以这种方式正确地做到这一点。
如果问题在某种程度上不合适,请原谅。 这是我第一次提问
评论者所说的,加上你可以用调用std::copy
来替换你的memcpy
以获得正确的行为:
std::copy (array, array + arraySize, tmpArray);
不要忘记#include <algorithm>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.