开发者

Is there a way to create a std::vector of dynamically allocated arrays?

For example, is it possible to have a std::vector of these arrays?

int *test1 = new int[10];
int *test2 = new int[20];
int *te开发者_开发百科st3 = new int[3];


Yes, it's possible, but why not just use vector<vector<int>> ? More flexible and less trouble.

If you insist on using arrays, shared_array in Boost could be helpful in reducing the manual work in managing the array memory.


Yes, it is possible. But since what you need is simple, make it simple :

std::vector <std::vector<int> > myArrayVector(numberOfArrays);
myArrayVector[0].resize(10);
myArrayVector[1].resize(20);
myArrayVector[2].resize(3);

Wherever you need to have an int*, use &myArrayVector[i][0], where i is the array index.


Yes.

std::vector<int*> vints;
vints.push_back(new int[10]);
vints.push_back(new int[20]);
vints.push_back(new int[3]);

But there is a problem: the vector can't remember the size of each dynamically allocated arrays.

So better use std:map as:

std::map<int, int*> arrayMap;
arrayMap[10] = new int[10];
arrayMap[20] = new int[20];
arrayMap[3] = new int[3];

The key of this map tells the size of the corresponding dynamically allocated array.

Yet better still is : vector of vector as:

std::vector<vector<int> > vecArray;

I would prefer the last approach, unless I've strong reason to go for the earlier ones, i.e container of dynamically allocated arrays.


It is possible. Try this.

vector<int*> vec;
vec.push_back(test1);
vec.push_back(test2);
vec.push_back(test3);

Edit: Do not forget release the memory before your vector goes out of the scope.

for(int i = 0; i < vec.size(); i++){
    delete [] vec[i];
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜