[問題] vector中物件copy的問題

看板C_and_CPP (C/C++)作者 (problem maker)時間13年前 (2012/08/30 12:41), 編輯推噓0(003)
留言3則, 2人參與, 最新討論串1/1
開發平台(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
當capacity不夠時,vector會把整段資料copy到另一塊空
08/30 15:01, 1F

08/30 15:02, , 2F
間去,你先call firstlvl.reserve(3)結果就不同了
08/30 15:02, 2F

08/30 15:09, , 3F
感謝啊....解決問題:)
08/30 15:09, 3F
文章代碼(AID): #1GFkxX-K (C_and_CPP)
文章代碼(AID): #1GFkxX-K (C_and_CPP)