考慮這段代碼。將值從一個向量複製到另一個向量(從書本)
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector <int *> test;
vector <int *> v;
int *a = new int;
int *b = new int;
*a = 1;
*b = 2;
v.push_back (a);
v.push_back (b);
for (int i = 0; i < 2; ++i)
{
int n = *v[i];
test.push_back (&n);
}
cout << *test[0] << " " << *test[1] << endl;
delete a;
delete b;
return 0;
}
問題的說法是:
「鑑於此代碼,回答下列問題:
爲什麼 「測試」 向量只包含2的
哪有?我們改變循環以正確地複製(只有for循環中的代碼)?「
我無法回答任何這些問題,所以有一點幫助將不勝感激。
在此先感謝。
你有你的想法任何想法'test'應包含哪些內容?無論如何,這本UB代碼在書中做了些什麼? – chris
題目是指針,所以我想這是學習 –
有教學指針更好的方式,其中最重要的是沒有機會炸掉你的計算機程序。 – chris