insert插入元素位置

sunnystorm 2007-11-01 11:39:16
#include <vector>
#include <string>
#include <list>
#include <iostream>
using namespace std;

int main (){
cout<<"Input words:"<<endl;
int s;
list<int> L;
list<int>::iterator it=L.begin();
while (cin>>s) {
L.insert(it,s);
}
it=L.begin();
while (it!=L.end()) {
cout<<*it<<endl;
++it;
}
return 0;
}
Primer C++ P319
说insert(it=L.begin(),s)和L.push_front (s);效果一样
验证了一下
发现insert 把元素放在后面
是不是书上错了
...全文
249 6 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
yuyunliuhen 2007-11-01
  • 打赏
  • 举报
回复
MSDN
aqiu348503 2007-11-01
  • 打赏
  • 举报
回复
每次insert之后,it已经不再指向begin,应该加入一句
while (cin> > s) {
L.insert(it,s);
it = L.begin();
}
飞哥 2007-11-01
  • 打赏
  • 举报
回复
你认为都到标准里去的东西还有有这种错误?

在指定的位置insert,你指定的位置是哪呢?开始位置,那就在开始位置加咯
sunnystorm 2007-11-01
  • 打赏
  • 举报
回复

语句应该为
it=L.insert(it,s);
sunnystorm 2007-11-01
  • 打赏
  • 举报
回复
L.insert(it,s);
把元素放到it指向位置之前的
sunnystorm 2007-11-01
  • 打赏
  • 举报
回复
如果输入1 2 3则输出
1
2
3
L.insert(it,s);
不是把it指向新插入元素位置吗?
那就应该输出
3
2
1

65,184

社区成员

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

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