[問題] vector中物件copy的問題
開發平台(Platform): (Ex: VC++, GCC, Linux, ...)
MacOSX10.6.8, xcode
額外使用到的函數庫(Library Used): (Ex: OpenGL, ...)
only STL
問題(Question):
為什麼copy constructor呼叫的次數不一樣
餵入的資料(Input):
預期的正確結果(Expected Output):
錯誤結果(Wrong Output):
程式碼(Code):(請善用置底文網頁, 記得排版)
class VectorTest {
public:
static int instanceCount;
int instanceId;
VectorTest() {instanceId = ++instanceCount;}
VectorTest(const VectorTest& right) {instanceId = right.instanceId+10;}
};
int VectorTest::instanceCount = 0;
int main (int argc, char * const argv[]) {
VectorTest vt1;
VectorTest vt2;
VectorTest vt3;
vector<VectorTest> firstlvl;
firstlvl.push_back(vt1);
firstlvl.push_back(vt2);
firstlvl.push_back(vt3);
for (int i = 0; i < firstlvl.size(); ++i) {
cout << firstlvl[i].instanceId << " ";
}
cout << endl;
vector<vector<VectorTest> > twoD;
twoD.push_back(firstlvl);
for (int i = 0; i < twoD.size(); i++) {
for (int j = 0; j < twoD[i].size(); j++) {
VectorTest& vt = twoD[i][j];
cout << vt.instanceId << " ";
}
cout << endl;
}
return 0;
}
執行結果是:
31 22 13 <----這是第一個cout loop
41 32 23 <----這是第二個cout loop
想請問的是 為什麼同樣vector裡的element, 被copy的次數似乎不一樣??
補充說明(Supplement):
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 69.110.234.65
→
08/30 15:01, , 1F
08/30 15:01, 1F
→
08/30 15:02, , 2F
08/30 15:02, 2F
→
08/30 15:09, , 3F
08/30 15:09, 3F
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章