谁能给解释一下这个循环?

king 2020 2008-11-08 04:53:28
钱能书上一个关于栈的例子:有个循环看不懂,大家帮忙解释。钱能的书跳跃真是太大了!
#include<iostream>
#include<fstream>
#include<sstream>
#include<stack>
using namespace std;
int main()
{
ifstream in("rail.txt");
for(int n,line=0;in>>n && in.ignore();)
{
cout<<(line++ ? "\n" : "");
for(string s;getline(in,s) && s!="0";)
{
istringstream sin(s);
stack<int> st;
for(int last=0,coach;sin>>coach;st.pop())
{
for(int p=last+1;p<=coach;++p) st.push(p);//这个循环是怎样执行的?并且进栈的是P,还是sin中的一位?last的值始终不变吗?coach的值又是什么?
if(last<coach) last=coach;
if(st.top()!=coach) break;
}
cout<<(!sin ? "Yes\n" : "No\n");
}
}
}
...全文
119 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
king 2020 2008-11-09
  • 打赏
  • 举报
回复
怎么没人进?
再顶!
king 2020 2008-11-09
  • 打赏
  • 举报
回复
还有这个循环希望列位大人解释明白,for(int p=last+1;p <=coach;++p) st.push(p);
例如取得的一行是3 2 1 5 4 的话,是不是说coach里存放的就是3 2 1 5 4 呢?
那么在循环的时候,p=1时,p<=3 2 1 5 4 呢,还是p<=3?,以此类推?
第一种情况我觉得有点不可能,所以认为是第二种。
但是如果是第二种的话,
当p=1 ,p<=3 ,p=1进栈
当p=2 ,p<=2 ,p=2进栈
当p=3 ,p<=1不满足,退出。
在外层循环将3 2 1出栈,然后再将5 4 进栈,然后再出栈,是这样么?
king 2020 2008-11-09
  • 打赏
  • 举报
回复
如果rail.txt文件内容 如下:
5
3 2 1 5 4
5 4 1 2 3
0
6
6 5 4 3 2 1
0
0
书上的结果是:
yes
no


yes
但在实际使用中,在第一行5的后面加一个空格,结果就变为:
yes
yes
no


yes
为什么呢?
xxgamexx 2008-11-09
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 King2005 的回复:]
还有这个循环希望列位大人解释明白,for(int p=last+1;p <=coach;++p) st.push(p);
例如取得的一行是3 2 1 5 4 的话,是不是说coach里存放的就是3 2 1 5 4 呢?
那么在循环的时候,p=1时,p <=3 2 1 5 4 呢,还是p <=3?,以此类推?
第一种情况我觉得有点不可能,所以认为是第二种。
但是如果是第二种的话,
当p=1 ,p <=3 ,p=1进栈
当p=2 ,p <=2 ,p=2进栈
当p=3 ,p <=1不满足,退出。
在外层循环将3 2 1出栈,…
[/Quote]

caoch只是个整型变量 每次for一次值都不一样 如这里的 3 2 1 5 4 第一次 caoch=3 然后 p<=3 第二次 caoch=2 然后 p<=2 ...

后面是否进出栈自己看条件 就明白了~

最后去实验!
frank_ll 2008-11-08
  • 打赏
  • 举报
回复
帮你调调格式


#include <iostream>
#include <fstream>
#include <sstream>
#include <stack>
using namespace std;
int main()
{
ifstream in("rail.txt");
for(int n,line=0;in>>n && in.ignore();)
{
cout < <(line++ ? "\n" : "");
for(string s;getline(in,s) && s!="0";)
{
istringstream sin(s);//sin是一个字符流
stack <int> st;
for(int last=0,coach;sin>>coach;st.pop())//last在初始化是为0,后面还是可以改变的。coach的值从sin中读出
{
for(int p=last+1;p <=coach;++p) st.push(p);//p小于coach就推出了,进栈的当然是p了
if(last <coach) last=coach;
if(st.top()!=coach) break;
}
cout < <(!sin ? "Yes\n" : "No\n");
}
}
}
帅得不敢出门 2008-11-08
  • 打赏
  • 举报
回复
int last=0,coach
coach是int
进栈的是P
last的值始终不变吗?
看条件 可能会变的
if(last <coach) last=coach;
xhs_lh04 2008-11-08
  • 打赏
  • 举报
回复
for(int p=last+1;p <=coach;++p) st.push(p);
这是个循环是p被初始化为last+1,进栈,直到p<输入值coach,每次循环后p+1

64,282

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧