我正在编写一个循环,如果队列不为空,循环将运行,我只是想知道是否需要在循环结束时包含break
。基本上每个循环都应该为队列中的每个元素运行,直到队列为空。
所以应该是以下哪一项 - 我只是不知道是否有正确的事情要做。
while (1)
{
/*process message from incoming queue*/
if (!msgs_inc.empty())
{
/*categorise incoming message into global map of outgoing messages*/
msgInfo current_msg = incMsgClassification(msgs_inc.front());
msgs_inc.pop();
clients_msg[current_msg.destID][current_msg.priorityLevel].push(current_msg);
}
}
或
while (1)
{
//Sleep(50000);
//cout << "success" << endl;
/*process message from incoming queue*/
if (!msgs_inc.empty())
{
/*categorise incoming message into global map of outgoing messages*/
msgInfo current_msg = incMsgClassification(msgs_inc.front());
msgs_inc.pop();
clients_msg[current_msg.destID][current_msg.priorityLevel].push(current_msg);
break;
}
}
答案 0 :(得分:8)
你想做的事情更清晰地写成......
while (!msgs_inc.empty()) // loop as long as queue still has elements
{
/*process message from incoming queue*/
/*categorise incoming message into global map of outgoing messages*/
msgInfo current_msg = incMsgClassification(msgs_inc.front());
msgs_inc.pop();
clients_msg[current_msg.destID][current_msg.priorityLevel].push(current_msg);
}
或者
while(1) {//infinite loop
while (!msgs_inc.empty()) // loop as long as queue still has elements
{
/*process message from incoming queue*/
/*categorise incoming message into global map of outgoing messages*/
msgInfo current_msg = incMsgClassification(msgs_inc.front());
msgs_inc.pop();
clients_msg[current_msg.destID][current_msg.priorityLevel].push(current_msg);
}
}
如果此函数在单独的线程上运行,这是更相关的,并且是该线程上运行的唯一一段代码。