如何引用std::list的前n个元素?

insnowind 2007-12-07 12:11:47
有一个std::list<int> cclst 里面有5000个元素,
现在有一个函数的参数是std::list<int>类型的,
但是我每次只想传1000个元素进去,就是把cclst中的元素分5次传进去,应该怎么写?
谢谢!
...全文
257 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
霁云 2007-12-07
  • 打赏
  • 举报
回复

void main()
{
std::list <int> cclst;
std::list <int> value(1000, 0);

// 方法一
for (int i = 0; i < 5; ++i)
cclst.insert(cclst.begin(), 1000, 1);

// 方法二
for (int j = 0; j < 5; ++j)
cclst.insert(cclst.begin(), value.begin(), value.end());

// 方法三
for (int k = 0; k < 5; ++k)
copy(value.begin(), value.end(), back_inserter<std::list <int> >(cclst));

copy(cclst.begin(), cclst.end(), ostream_iterator<int>(cout, " "));
}
ryfdizuo 2007-12-07
  • 打赏
  • 举报
回复

#include <iostream>
#include <list>
using namespace std;

void test(list<int> IntList)
{
int i;
const int count=1000;
static list<int>::iterator Iter=IntList.begin();
cout<<*Iter<<endl;
for(i=0,Iter; Iter!=IntList.end()&&( i<count ); Iter++, i++)
cout<<*Iter<<" ";
cout<<"i :" <<i<<endl;
cout<<"The last one is: "<<*Iter<<endl;
}

int main()
{
list<int> cclist;
list<int>::iterator Iter=cclist.begin();
for(int i=0; i<2000; i++)
cclist.push_back(i);
cout<<cclist.size()<<endl;
test(cclist);
test(cclist);

return 0;
}
函数里面的static Iter有点问题,当第二次进入函数的时候并不是从第1001个元素开始;
lx的兄弟们帮忙改进一下吧,^_^
insnowind 2007-12-07
  • 打赏
  • 举报
回复
谢谢一楼的兄弟的解答!
虽然二楼的兄弟的答案还不是很完美,但是看出来很努力!
所以给二楼20分!

64,675

社区成员

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

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