[英]I can get objects from a list and copy them, but how do I delete the objects I copied?
I'm trying to find all the processes in the blockedProcess list with the specified event number, copy them into a transferList, and then remove them. 我试图在具有指定事件编号的blockedProcess列表中找到所有进程,将它们复制到transferList中,然后将其删除。 Copying and moving the Process objects works fine, but I can't figure out how to remove those Process objects from blockedProcess afterwards. 复制和移动Process对象效果很好,但是后来我不知道如何从blockedProcess中删除那些Process对象。
ProcessQueue findEventFlag(int eventnum)
{
ProcessQueue transferProcess;
Process process;
list<Process>::iterator it;
for (it = blockedProcess.begin(); it != blockedProcess.end(); it++)
{
process = *it;
if (process.getEvent() == eventnum)
{
process.setState("READY");
process.setEvent(-1);
transferProcess.enqueue(process);
}
}
return transferProcess;
}
Building on the comments, try this (which relies on the fact that std::list::erase
conveniently returns an iterator to the next item in the list): 在注释的基础上,尝试以下操作(这取决于std::list::erase
方便地将迭代器返回std::list::erase
中的下一项的事实):
ProcessQueue findEventFlag(int eventnum)
{
ProcessQueue transferProcess;
Process process;
list<Process>::iterator it = blockedProcess.begin();
while (it != blockedProcess.end())
{
process = *it;
if (process.getEvent() == eventnum)
{
process.setState("READY");
process.setEvent(-1);
transferProcess.enqueue(process);
it = process.Erase (it);
}
else
it++;
}
return transferProcess;
}
You can also transfer an element from one list to another with std::list::splice
which would avoid copying your process
object and might therefore be more efficient, something like: 您还可以使用std::list::splice
将元素从一个列表转移到另一个std::list::splice
,这将避免复制process
对象,因此可能会更高效,例如:
ProcessQueue findEventFlag(int eventnum)
{
ProcessQueue transferProcess;
Process process;
list<Process>::iterator it = blockedProcess.begin();
while (it != blockedProcess.end())
{
process = *it;
list<Process>::iterator next = std::next (it);
if (process.getEvent() == eventnum)
{
process.setState("READY");
process.setEvent(-1);
transferProcess.splice(transferProcess.begin (), blockedProcess, it);
}
it = next;
}
return transferProcess;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.