解读一段C++代码

来源:百度知道 编辑:UC知道 时间:2024/06/17 19:42:51
#include <iostream>
#include <stack>
using namespace std;

bool stack_pop(stack<int> &st, int num, int data[], int &pos)
{
if(num == 0) return true;
if(st.size() < num) return false;
for(int i=0; i<num; ++i)
{
data[pos++] = (int)(st.top());
st.pop();
}
}

int main()
{
int A=0, B=0, C=0, Total=0;
int output[4], pos;
for(A=0; A<2; ++A)
for(B=0; B<3; ++B)
for(C=0; C<4; ++C)
{
pos = 0;
stack<int> st;
st.push(1);
stack_pop(st, A, output, pos);
st.push(2);
if(!stack_pop(st, B, output, pos)) continue;
st.push(3);
if(!stack_pop(st, C, output, pos)) continue;
st.push(4);
stack_pop(st, st.size(), output, pos);
for(int i=0;i<4;++i) cout<<output[i];
cout<<endl;
++Total;
}
cout<<"Total numbers:"<<Total<&l

我在这里给你加一些注释:
#include <iostream>
#include <stack>
using namespace std;
/******************************************************/
//功能:出栈函数,并判断能否正确出栈
//参数:num,出栈次数
// data,保存出栈数据
// pos,保存位置
/******************************************************/
bool stack_pop(stack<int> &st, int num, int data[], int &pos)
{
if(num == 0) return true;
if(st.size() < num) return false;
for(int i=0; i<num; ++i)
{
data[pos++] = (int)(st.top()); //保存出栈数据
st.pop(); //出栈
}
}

int main()
{
int A=0, B=0, C=0, Total=0;
int output[4], pos; //output是缓存,pos是位置指针
for(A=0; A<2; ++A) //A出栈情况,0:不出栈 ,1:出栈
for(B=0; B<3; ++B) //B出栈情况,0:不出栈 ,1:出栈一次,2:出栈两次
for(C=0; C<4; ++C) //C出栈情况,0:不出栈 ,1:出栈一次,2:出栈两次,3:出栈三次
{
pos = 0; //将pos设为0,是为了清空缓存
stack<int> st;
st.push(1); //st.push(1)....s