看板 C_and_CPP 關於我們 聯絡資訊
開發平台(Platform): (Ex: Win10, Linux, ...) win10 編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出) GCC 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) <vector> 問題(Question): 因為第一次使用vector (作業需要 想要做到的事情是 我有類似4個Set ex: vector<Zone> Target0,Target1,Target2,Target3 Zone裡面的struct存了一些資料 struct Zone{//此為各網格之struct int row; int col; int id; int status; bool isB;}; 每次判斷後set會移動 舉例:一開始所有值都在Target0 中 Target0={0,1,2,3,....23} 其他Target1,2,3都是 NULL 假設做完一個interation後 要使 3 從 target0 移到 target1 要怎麼樣最好呢 ex:Target0={0,1,2,3,....23}-{3} = {0,1,2,4....,23} Target1={3} 程式碼(Code):(請善用置底文網頁, 記得排版,禁止使用圖檔) //先把所有值放到Target0 for(i=0;i<M;i++) for(j=0;j<N;j++){ Zone* node=new Zone; node->row=i; node->col=j; node->id=i*N+j; if(SMap[i][j]==1){ node->isB=1; }else {node->isB=0;} node->status=0; Target0.push_back(*node); } //想把 Target0 的 第id個值 移到 Target3中 vector<Zone>::iterator it, end; //建立for迴圈要用的疊代器(?) 不確定是不是這樣 id=(row-1)*N+col; //計算id Zone* node=Target0.[id]; //將Target中 的第id個值存到node中 Target3.push_back(node); //將node放入target3中 for(it=Target0.begin(); it!=Target0.end(); ++it)//在target0中找第id個值 if(it->id==id) it = Target0.erase(it) //如果找到 把第id個值刪掉 這是我目前的想法 但compile下來會到一半就卡住了 另外想請問 如果要取Target4中的最後一個值來使用 (之後要pop_back if(Target4.empty==0){ //Target4 非空 vector<Zone>::iterator now=Target4.end()-1; row=now->row; col=now->col; id=row*N+col; } 用這樣的方式對嗎 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 1.163.23.107 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1525871601.A.A04.html
KanzakiHAria: 請學會使用debugger 05/09 21:45
shadow0326: compile卡住是指compile error? 那請貼上錯誤訊息 05/09 23:32
shadow0326: 然後在forloop裡erase不能這樣寫 05/09 23:34
shadow0326: 隨便找個參考寫法給你 https://tinyurl.com/yat9fzsm 05/09 23:35
感謝s大 後來發現是erase時會卡住 for(it=Target3.begin(); it!=Target3.end(); ){ if(it->id==id){ it=Target3.erase(it); break; } else ++it; } 改成類似這樣就可以了 不加break的化 會一直重複迴圈QQ ※ 編輯: qazwsx879345 (114.44.69.142), 05/10/2018 04:30:05 ※ 編輯: qazwsx879345 (114.44.69.142), 05/10/2018 04:30:16
taies: 可以試著用std::find_if幫找vector裡的東西 05/10 08:18
Jockey66666: 用earse加std::remove_if就不用for loop了 05/10 09:30
謝謝大家的建議,我會用一些簡單的例子試試看 ※ 編輯: qazwsx879345 (114.44.69.142), 05/10/2018 11:21:13