繁体   English   中英

如何释放动态分配的向量?

[英]How to free dynamically allocated vector?

我试图创建向量int的向量,但我困惑于如何释放动态分配的向量。

以下是我的代码:

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;

您不需要任何指针或newdelete 这些是高级概念,在此简单程序中没有任何地位。

vector<vector<int>> i;

for (...) { 
    vector<int> j;
    // fill up j
    i.push_back(j);
}

请记住,向量的向量在概念上与整数的向量没有什么不同。 当您需要填充vector<int>时,您无需启动new'ing和delete'ing int。 使用vector<X>时,也不需要对任何X都这样做。

i.push_back(*j);

不推动指针; 它复制了向量。

完成后,您可以

delete j;

然后那里。

(当然,如果将i更改为存储指针 ,则故事将完全不同。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM