[問題] vector刪除問題

看板C_and_CPP作者 (徘徊在抉擇之間)時間7年前 (2016/12/14 22:08), 編輯推噓3(308)
留言11則, 5人參與, 最新討論串1/1
開發平台(Platform): (Ex: Win10, Linux, ...) Win7 編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出) VC++ 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) std::vector 問題(Question): assign value完之後 最後如何delete 餵入的資料(Input): 會有5個structure A 裡面有一個float 以及另一結構4份資料 預期的正確結果(Expected Output): 資料memory都清空 錯誤結果(Wrong Output): 資料沒有全放掉 程式碼(Code):(請善用置底文網頁, 記得排版) struct point { int X; int Y; }; struct A { float fSpeed; std::vector<point*>pointVec; }; // Assign value A* pA = new A[5]; for(int i = 0 ; i < 5 ; i++) { pA[i]->fSpeed = 2.0; for(int nPointIndex = 0 ; nPointIndex < 4 ; nPointIndex++) { point* pPoint = new point(); pPoint.X = ... pPoint.Y = ... pA[i]->pointVec.push_back(pPoint); } } // Delete Method 1 if(pA) { delete [] pA; pA = NULL; } Method 2 for(int i = 0 ; i < 5 ; i++) { auto itr = pA[i]->pointVec.begin(); for(; itr != pA[i]->pointVec.end(); itr++) { delete &itr; } } 補充說明(Supplement): 以上兩種方法會都清空嗎? 還是有沒有更好的delete方式 謝謝 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 111.240.175.113 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1481724480.A.52E.html

12/14 23:16, , 1F
你都會auto了 怎麼不用range loop...
12/14 23:16, 1F

12/14 23:19, , 2F
而且可以改用 smart_pointer阿...
12/14 23:19, 2F

12/15 02:39, , 3F
兩個都要用 1刪A 2刪point 先2在1
12/15 02:39, 3F

12/15 02:40, , 4F
2怪怪的 delete *itr?
12/15 02:40, 4F

12/15 09:08, , 5F
沒規定要用raw pointer 的話就用smart pointer 吧大大
12/15 09:08, 5F

12/15 20:41, , 6F
另外問原PO 你這種方式是要實作Observer design pattern?
12/15 20:41, 6F

12/15 20:42, , 7F
goo.gl/MtzcrP 這邊有類似你的應用 你可以看一下人家怎麼
12/15 20:42, 7F

12/15 20:42, , 8F
釋放記憶體的
12/15 20:42, 8F

12/15 23:29, , 9F
好的 謝謝 再研究一下
12/15 23:29, 9F

12/18 14:48, , 10F
都vec了就vec吧,刻意使用vec模擬嗎QQ
12/18 14:48, 10F

12/18 14:49, , 11F
de [] 配 new [] 沒有方括配沒有方括
12/18 14:49, 11F
文章代碼(AID): #1OKL90Kk (C_and_CPP)