调整数组大小并添加元素 C++
resize array and add element c++
嘿,我知道这很简单,但由于某种原因,我比我想象的更艰难。我试图做的是,如果我的动态数组的大小等于其中元素的实际数量(意味着它是满的(,那么我想将数组的大小加倍并添加元素
int add_element(int *array, int size , int &count)
{
int temp;
cout << "What number do you want to add ? " << endl;
cin >> temp;
if(count = size)
{
copy(array, size);
count++;
array[count] = temp;
}
return count;
}
void copy(int *oldArr , int size)
{
int temp = size * 2;
int *newArr = new int[temp];
for (int i = 0; i < size; i++)
{
newArr[i] = oldArr[i];
}
//delete[] oldArr;
oldArr = NULL;
oldArr = newArr;
delete[] oldArr;
我遇到的问题是,实际上并没有将数组的大小加倍,因为当我尝试查找元素时,它只返回地址空间。 任何帮助将不胜感激
***********编辑********* 我继续进行这些更改,但我的数组似乎仍然没有改变大小
void add_element(int* &array, int size , int &count)
{
int temp;
cout << "What number do you want to add ? " << endl;
cin >> temp;
if(count == size)
{
copy(array, size);
count++;
array[count] = temp;
}
}
void copy(int* &oldArr , int size)
{
int temp = size * 2;
int *newArr = new int[temp];
for (int i = 0; i < size; i++)
{
newArr[i] = oldArr[i];
}
delete[] oldArr;
oldArr = newArr;
代码中有几个错误。
首先,在add_element
中,您想测试项目计数是否等于数组大小,但您不小心覆盖了count
变量:
if(count = size) // this assigns count
应替换为
if(count == size)
其次,删除新分配的阵列而不是旧阵列:
oldArr = newArr;
delete[] oldArr; // this will effectively deallocate newArr
您应该更改这些行的顺序:
delete[] oldArr; // it deletes oldArr
oldArr = newArr; // and then points it to newArr
第三,按值将指针传递给数组。这样,当分配新数组时,您将无法将新数组的地址返回给函数的调用方。您应该通过引用传递数组指针,类似于count
:
int add_element(int* &array, int size, int &count)
和
void copy(int* &oldArr, int size)
第四,从函数add_element
返回两次count
:既作为返回值,又作为 In-Out 参数。虽然,这在技术上不是问题,但绝对没有必要。我建议更改add_element
以返回void
.
更新:
最后,但至少不是,我忽略了第五个问题。与需要从函数返回新数组指针的方式类似,数组大小也必须这样做。因此size
应该通过引用传递,并且应该正确更新:
int add_element(int* &array, int &size, int &count)
和
void copy(int* &oldArr, int &size) { // pass size by reference
int temp = size * 2;
// ...
oldArr = newArr;
size = temp; // update size
}
相关文章:
- 有没有办法向这个向量添加元素?
- 如何在提升间进程中构建具有给定计数的向量并向其添加元素
- 如何在 Arduino 字符串的开头添加元素.类似于 JS unshift();
- C++向数组添加元素并调整数组大小
- 我无法向 c++ 添加元素
- BST 不添加元素
- 调整数组大小并添加元素 C++
- 向向量添加元素
- 如何在不使用标准算法的情况下在排序向量中添加 c 元素?
- 双链接列表添加元素不起作用,不知何故它总是保持为空
- 当我向 vector<int *> 添加元素时,我遇到了一些问题
- 动态地添加元素
- 静态2D数组,添加元素
- 在一个类中向向量添加元素不适用于其他类
- 在数组中添加元素将不接受类似的元素
- STD :: MAP-使用下标操作员与插入方法添加元素
- 动态数组添加元素而不创建结构变量/对象
- 以下向 c++ 向量添加元素的方法有什么区别
- 如何在 std::map 中添加元素自己进行分配
- C++在向量中添加元素的双精度