我需要爲循環,直到隊列執行的是空 我的代碼如何爲循環,直到隊列執行的emptyin C++
queue<string> q;
for(int i=0;i<q.size(),i++)
{
// some operation goes here
// some datas are added to queue
}
我需要爲循環,直到隊列執行的是空 我的代碼如何爲循環,直到隊列執行的emptyin C++
queue<string> q;
for(int i=0;i<q.size(),i++)
{
// some operation goes here
// some datas are added to queue
}
while (!q.empty())
{
std::string str = q.front();
// TODO: do something with str.
q.pop();
}
其更好地使用while循環爲:
while (!q.empty()) {
// do operations.
}
但是,如果在聲明隊列後立即執行此操作,則不會進入循環,因爲創建時隊列將爲空。在這種情況下,你可以使用一個do-while循環爲:
queue<string> q;
do {
// enqueue and dequeue here.
}while (!q.empty());
while (! q.empty())
{
}
是其可能的。
int size=q.size();
for(int i=0;i<size;i++){
std::cout<<"\nCell - "<< q.front();
q.pop();
}
但人們大多避免使用for循環,因爲排隊的每一次規模將針對循環計數器,其中n/2 elemets中間彈出迭代將結束ubruptly的大小將變成n檢查/ 2,我也是n/2。下面的例子。
for(int i=0;i<q.size();i++){
std::cout<<"\nCell - "<< q.front();
std::cout<<"\tSize: - "<< q.size()<<" I value:"<<i;
q.pop();
}
這是與最佳答案相同的代碼,但使用for
循環。它對我來說看起來更清潔。
for (; !q.empty(); q.pop())
{
auto& str = q.front();
// TODO: do something with str.
}
請將解釋添加到您的答案。 for – 2017-07-12 12:09:32
for循環不需要實例/啓動一個變量,所以我們只使用';'告訴它什麼都不做,for的條件是直到隊列不是空的,在循環的結尾;從隊列中彈出該項目 – Sherlock 2017-09-30 21:27:20