ベクトル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;
なぜ最初に動的に割り当てる必要がありますか?理由はありません。 – Slava
'ベクトル< vector>'はベクトルではないベクトルポインタのリストを保持し、 'std :: vector'はそのオブジェクトのメモリをそれにプッシュします。 –
最初に 'new'を使用しない方が良いでしょう。 'j'を'ベクトル j; 'に変更し、ループ本文を' j.push_back(10);に変更します。 i.push_back(std :: move(j)); '。 –