BAD_ALLOC错误实现向量调整大小函数时
bad_alloc error when implementing vector resize function
我正在尝试在C 中实现Vector::resize()
功能。我认为我处理了每种情况,但仍然会遇到bad_alloc
错误。此调整大小实施中的三种情况:
- 当
new_size
小于old_size
时(在我的代码中,size
); - 当
new_size
大于size
,但小于容量; - 当
new_size
大于容量
时
这是我的代码:
void Vector::resize(int new_size)
{
//if the new_size is smaller, make the size smaller, don't need to worry about memory
//the content is reduced to its first n elements
//remove those beyond and destroy them
if(new_size < size){
for(int i = size-1; i > new_size; i--){
erase(i);
}
size = new_size;
}
//if the new_size is bigger
//case 1: new_size is smaller than capacity
//inserting at the end of as many elements as needed
if(new_size > size && new_size < capacity){
for(int i=size; i < new_size; i++){
insert(i, 0.0);
}
size = new_size;
}
//case 2: new_size is greater than capacity
//increase the capacity of the container
//increase the capacity to new_size
double *tmp_data = new double(new_size);
//transfer data to tmp_data
for(int i=0; i < size; i++)
{
tmp_data[i] = data[i];
}
data = tmp_data;
delete [] data;
size = new_size;
capacity = new_size;
}
此代码有几件事。首先跳出的一个是:
//increase the capacity to new_size
double *tmp_data = new double(new_size);
您打算分配一个数组,但实际上是在分配单个double
。你的意思是:
double *tmp_data = new double[new_size];
虽然,一旦您修复了...
data = tmp_data;
delete [] data;
您想以相反的顺序进行操作,否则您要留下删除的成员。
,一旦您修复了,您就想尽早从案件中 return
。您有三个案例(如您的评论所建议的那样),并且在您实际需要的情况下(即案例#3),您只想重新分配。根据,您在所有情况下都重新分配。
正如巴里指出的那样,您有一些错误。
这是您的代码,有一些建议:
void Vector::resize(int new_size)
{
if(new_size <= size) { // use "<=" here
// if you are dealing with doubles, what is there to erase?
// (I would remove that loop)
for(int i = size-1; i > new_size; i--){
erase(i);
}
size = new_size;
return; // you're done here, you can return
}
if(new_size <= capacity) { // again "<=", if you return, then no need for anything more
// "insert()" sounds confusing, you're doing a set() here
for(int i=size; i < new_size; i++){
insert(i, 0.0);
}
size = new_size;
return; // again, you can now return, you're done
}
double *tmp_data = new double(new_size);
// you could use std::copy() here
for(int i=0; i < size; i++)
{
tmp_data[i] = data[i];
}
// as indicated by Barry, you could inverse these
delete [] data;
data = tmp_data;
size = new_size;
capacity = new_size;
}
我删除了您的所有评论,并为您仔细阅读。
另一种处理3个案例的方法是使用Else关键字这样:
if(new_size <= size) {
...
} else if(new_size <= capacity) {
...
} else {
...
}
,要明确说明,您可以从每个...
案例中拨打三个子函数。这样,您可以看到resize()
函数的主要逻辑。
相关文章:
- 如何在 LLVM 模块中调整函数位置
- 为什么保守调整大小不适用于函数中的 Ref 变量?
- 使用Bicubic C 的调整大小函数的OPENCV代码流是什么?
- 通过新的后传递后创建的动态数组的错误以调整函数
- 将函数上调整到基类参数的另一个
- C++中向量容器的大小和调整大小函数
- bool值不在腔函数函数中重新调整false,c
- OPENCV C 调整大小函数:新宽度应乘以3
- C++:为什么 boost::p tr_vector 调整大小需要对象具有默认构造函数
- 将返回 std::future 的函数调整为<T> std::future<U>
- BAD_ALLOC错误实现向量调整大小函数时
- 在 std::vector 上调整大小不会调用移动构造函数
- opencv 调整函数大小执行时间慢
- 当函数重新调整通过引用传递时检查对象是否存在
- 如何在使用向量调整大小时调用非默认构造函数
- 尝试在矢量类中创建调整大小函数
- 一个调整任何动态数组大小的函数
- vector.resize()方法在调整大小时调用默认的元素构造函数
- 在c++中调整vector大小时调用一次类构造函数
- 如何调整函数