For loop C++;-使用for()循环时队列pop无法正常工作
在使用STL队列和For loop C++;-使用for()循环时队列pop无法正常工作,for-loop,visual-c++,while-loop,queue,For Loop,Visual C++,While Loop,Queue,在使用STL队列和for循环编写简单代码时,我遇到了一个问题。我的过程很简单:将数字作为字符串,将它们转换为队列元素并显示它们 我的代码如下: #include<iostream> #include<queue> #include<string> //#include<cctype> using namespace std; //int to_words(int i); //int to_words_one(queue<int> &a
for
循环编写简单代码时,我遇到了一个问题。我的过程很简单:将数字作为字符串,将它们转换为队列元素并显示它们
我的代码如下:
#include<iostream>
#include<queue>
#include<string>
//#include<cctype>
using namespace std;
//int to_words(int i);
//int to_words_one(queue<int> &q);
int main()
{
queue<int> q;
string s;
cout << "Enter a number not more than 12 digits : ";
getline(cin, s, '\n');
for (int i = 0; i < s.length(); i++)
{
if (!isdigit(s[i]))
{
cout << "Not a valid number." << endl;
s.clear();
break;
}
}
if(s.size() > 0)
for (int i = 0; i < s.length(); i++)
q.push(s[i] - '0');
while (!q.empty())
{
cout << q.front();
q.pop();
}
system("PAUSE");
}
它不能正常工作!它只显示并弹出一些第一个元素,而不是队列中的所有元素,并提示您按任意键继续。请告诉我为什么会这样?
while(!q.empty())
和for()
循环的工作原理是否应该类似?通过调用queue::pop
队列的大小会减小,所以假设您在for循环的第一次迭代中输入8位q.size()
返回8,然后比较j<8
这是真的,j
增加,队列大小减小。在下一次循环中,比较j<7
,其中j
为1。进行第2次、第3次迭代。。。在第4次迭代之后,j
计数器的值为4,队列的大小也为4,因此条件j<4
返回false,并且只打印了4位数字。问题在于,q.size()
在每次q.pop()
之后都会减小,并且在for循环的每次迭代中都会进行计算。例如,假设队列中有6个元素,后续迭代中的For循环状态如下:
- i=0,q.size()=6
- i=1,q.size()=5
- i=2,q.size()=4
- i=3,q.size()=3
q.size()
保存到变量,如下所示:
int q_size = q.size();
for (int i = 0; i < q_size; i++) {
// do something
}
int q_size=q.size();
对于(int i=0;i
int q_size = q.size();
for (int i = 0; i < q_size; i++) {
// do something
}