分配更多的内存动态分配的数组 [英] Allocate more memory for dynamically allocated array
问题描述
我的C ++算法未知大小(它由一个检测图像一个在颗粒,并且我不知道有多少粒子将被检测算法完成其工作之前)获得的数据。
所以,首先我要分配,说,阵列10000元,并在加工过程中,如果需要的话,分配另一个要素10000多次。
My C++ algorithm obtains data with unknown size (it detects particles on the image one by one, and I cannot know how many particles will be detected before this algorithm finishes its work). So, first I want to allocate, say, array with 10000 elements, and during the processing, if necessary, allocate another 10000 elements several times.
下面是我试过了,这是行不通的:
Here is what I tried, it doesn't work:
#include <iostream>
using namespace std;
int main(){
int n = 3;
int m = 3;
float *a = new float[3];
a[0] = 0;
a[1] = 1;
a[2] = 2;
float *b = a + 2;
b = new float[3];
b[0] = 4;
b[1] = 5;
cout << a[3] << endl;
}
其结果是,我得到了负无穷大。当然,我可以在不同的阵列处理这个问题,我可以分配一次巨大的内存量。我需要通过检测的数据后的功能全阵列,所以,作为结果,我想有一个大的阵列
As a result, I got minus infinity. Of course, I can handle this in different arrays, I can allocate a huge amount of memory once. I need to pass full array of detected data to the function after, so, as a result, I want to have one big array.
但尽管如此,有没有增加你的动态分配的方式大小的方法吗?我想在一个玩具的例子是3增加阵列 A
元素的数量,所以它会有 6
元素。
But still, is there a way to increase the size of your dynamically allocated way? What I want in a toy example is to increase number of elements in array a
by 3, so it will have 6
elements.
在Matlab的是绝对有可能的。什么C ++?
In Matlab it is absolutely possible. What about C++?
感谢
推荐答案
没有,你可以在不增加数组的大小。如果你想使用一个数组,你必须分配一个新的块,够大了全新的数组,并删除旧阵列之前,整个复制现有元素。或者你可以使用不保存其元素连续一个更复杂的数据结构。
No, you can't increase the size of an array. If you want to use an array, you'll have to allocate a new block, large enough for the whole new array, and copy the existing elements across before deleting the old array. Or you could use a more complicated data structure that doesn't store its elements contiguously.
幸运的是,标准库有集装箱自动处理;包括矢量
,可调整大小的数组。
Luckily, the standard library has containers to handle this automatically; including vector
, a resizable array.
std::vector<float> a(3);
a[0] = 0;
a[1] = 1;
a[2] = 2;
// you can resize it by specifying a new size
a.resize(4);
a[3] = 3;
// or by appending new elements
a.push_back(4);
这篇关于分配更多的内存动态分配的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!