我试图创建vector int的vector,但我感到困惑,如何在之后释放动态分配的vector。
以下是我的代码:
vector<int> *j;
vector< vector<int> > i; //vector of vector<int>
int c; //offset of the number
cin.ignore();
for(int count = 0; count < cas; count++ )
{
c = 0;
char line[1000];
j = new vector<int>;
cin.getline(line, 1000);
//tokenize the input string which separate by space “ ”
char *p = strtok(line, " ");
while(p != NULL)
{
n[c] = string(p);
c++;
p = strtok(NULL, " ");
}
//convert the string input to integer for further calculation
for(int m = 0; m < c; m++)
{
(*j).push_back(atoi(n[m].c_str()));
}
i.push_back(*j);
}
//this is the way i try to free the allocated vector, and i get segmentation fault for this
j = &i[0];
delete [] j;
您不需要任何指针或new
或delete
。这些是高级概念,在此简单程序中没有任何地位。
vector<vector<int>> i;
for (...) {
vector<int> j;
// fill up j
i.push_back(j);
}
请记住,向量的向量在概念上与整数的向量没有什么不同。需要填写时,您无需启动new'ing和delete'ing int vector<int>
。X
当您使用时,也不需要这样做vector<X>
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句