[問題] vector的移動
看板C_and_CPP (C/C++)作者qazwsx879345 (Rajon Rondo)時間7年前 (2018/05/09 21:13)推噓0(0推 0噓 6→)留言6則, 4人參與討論串1/1
開發平台(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
→
05/09 21:45,
7年前
, 1F
05/09 21:45, 1F
→
05/09 23:32,
7年前
, 2F
05/09 23:32, 2F
→
05/09 23:34,
7年前
, 3F
05/09 23:34, 3F
→
05/09 23:35,
7年前
, 4F
05/09 23:35, 4F
感謝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
→
05/10 08:18,
7年前
, 5F
05/10 08:18, 5F
→
05/10 09:30,
7年前
, 6F
05/10 09:30, 6F
謝謝大家的建議,我會用一些簡單的例子試試看
※ 編輯: qazwsx879345 (114.44.69.142), 05/10/2018 11:21:13
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章