作者qazwsx879345 (Rajon Rondo)
看板C_and_CPP
标题[问题] vector的移动
时间Wed May 9 21:13:17 2018
开发平台(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://webptt.com/cn.aspx?n=bbs/C_and_CPP/M.1525871601.A.A04.html
1F:→ KanzakiHAria: 请学会使用debugger 05/09 21:45
2F:→ shadow0326: compile卡住是指compile error? 那请贴上错误讯息 05/09 23:32
3F:→ shadow0326: 然後在forloop里erase不能这样写 05/09 23:34
感谢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
5F:→ taies: 可以试着用std::find_if帮找vector里的东西 05/10 08:18
6F:→ Jockey66666: 用earse加std::remove_if就不用for loop了 05/10 09:30
谢谢大家的建议,我会用一些简单的例子试试看
※ 编辑: qazwsx879345 (114.44.69.142), 05/10/2018 11:21:13