【发布时间】:2011-04-26 14:15:17
【问题描述】:
例如,是否有可能拥有这些数组的 std::vector?
int *test1 = new int[10];
int *test2 = new int[20];
int *test3 = new int[3];
【问题讨论】:
标签: c++ arrays dynamic vector allocation
例如,是否有可能拥有这些数组的 std::vector?
int *test1 = new int[10];
int *test2 = new int[20];
int *test3 = new int[3];
【问题讨论】:
标签: c++ arrays dynamic vector allocation
是的,这是可能的,但为什么不直接使用 vector<vector<int>> 呢?更灵活,更少麻烦。
如果您坚持使用数组,Boost 中的shared_array 可能有助于减少管理数组内存的手动工作。
【讨论】:
scoped_array 不能进入 std::vector,唉。
vectors就更简单了。您编写的每个new 都会引入额外的异常处理问题和内存管理复杂性。
是的,这是可能的。但是既然你需要的很简单,那就让它简单吧:
std::vector <std::vector<int> > myArrayVector(numberOfArrays);
myArrayVector[0].resize(10);
myArrayVector[1].resize(20);
myArrayVector[2].resize(3);
无论您在哪里需要一个 int*,都可以使用 &myArrayVector[i][0],其中 i 是数组索引。
【讨论】:
是的。
std::vector<int*> vints;
vints.push_back(new int[10]);
vints.push_back(new int[20]);
vints.push_back(new int[3]);
但是有一个问题:vector无法记住每个动态分配的数组的大小。
所以最好使用std:map:
std::map<int, int*> arrayMap;
arrayMap[10] = new int[10];
arrayMap[20] = new int[20];
arrayMap[3] = new int[3];
这个map的key告诉了对应的动态分配数组的大小。
更好的是:向量的向量为:
std::vector<vector<int> > vecArray;
我更喜欢最后一种方法,除非我有充分的理由选择较早的方法,即 动态 分配数组的容器。
【讨论】:
std::map!
std::map 不起作用。但问题是,我知道所有可能的情况吗?不,所以它只是给出一些想法。顺便说一句,这是你投反对票的原因吗?
这是可能的。试试这个。
vector<int*> vec;
vec.push_back(test1);
vec.push_back(test2);
vec.push_back(test3);
编辑: 不要忘记在你的向量超出范围之前释放内存。
for(int i = 0; i < vec.size(); i++){
delete [] vec[i];
}
【讨论】:
vec超出范围时它会泄漏。