谁能帮我看看这个小程序?

Botton2008 2004-06-25 05:03:19
问题:

请写一个程序,使它接受下列定义:
int ia[] = {0, 1, 1, 2, 3, 5, 8, 13, 21, 55, 89}
list<int> ilist(ia, ia+11)
用单个iterator形式的erase()删除ilist中所有奇数位置的元素。


我的源程序如下:

#include <iostream>
#include <list>
#include <conio.h>

using namespace std;

int main()
{
int ia[] = {0, 1, 1, 2, 3, 5, 8, 13, 21, 55, 89};
list<int> ilist(ia, ia + 11);

int size = ilist.size();
list<int>::iterator iter;

//show the elements of ilist
cout << "ilist("<< size <<"): {";

int i = size;
for (iter = ilist.begin(); iter != ilist.end(); ++iter, --i) {
cout << *iter;
if (i != 1)
cout << ", ";
}

cout << "}" << endl;

//delete the elements in odd position
i = 1;
for (iter = ilist.begin(); i < size && iter != ilist.end(); ++iter, ++i)
if ( i % 2 )
ilist.erase(iter);

size = ilist.size();
i = size;

//show the result
cout << "\nAfter the deletion operation...\n"
<< "ilist("<< size <<"): {";

for (iter = ilist.begin(); iter != ilist.end(); ++iter, --i) {
cout << *iter;
if (i != 1)
cout << ", ";
}

cout << "}" << endl;

cout << "\nPress any key to exit..." << endl;
getch();

return 0;
}

程序调试环境:Dev-C++ 4.9.8.0

运行结果:程序异常中止
...全文
67 点赞 收藏 3
写回复
3 条回复
Botton2008 2004年06月25日
谢谢Jinhao和Downcast,我终于知道问题出在什么地方了!:)
回复 点赞
downcast 2004年06月25日
这样也可以
//delete the elements in odd position
iter = ilist.begin();
i = 1;
while (iter != ilist.end()) {
if ( i % 2 ) {
ilist.erase(iter++);
i++;
}
else {
iter++;
i++;
}
}

或者把需要的iterator先集中起来再一起处理也可以
回复 点赞
Jinhao 2004年06月25日
这个是老问题了,在list,vector,等等这些容器里,iterator会出现失效的情况

int main() {
int ia[] = {0, 1, 1, 2, 3, 5, 8, 13, 21, 55, 89};
list<int> ilist(ia, ia + 11);

int size = ilist.size();
list<int>::iterator iter;

//show the elements of ilist
cout << "ilist("<< size <<"): {";

int i = size;
for (iter = ilist.begin(); iter != ilist.end(); ++iter, --i) {
cout << *iter;
if (i != 1)
cout << ", ";
}

cout << "}" << endl;

//delete the elements in odd position
i = 1;
for (iter = ilist.begin(); i < size && iter != ilist.end(); ++iter, ++i)
{
list<int>::iterator lastiter;
if ( i % 2 )
{
lastiter=iter--;
ilist.erase(lastiter); //lastiter被erase后就无效了
}
}
size = ilist.size();
i = size;

//show the result
cout << "\nAfter the deletion operation...\n"
<< "ilist("<< size <<"): {";

for (iter = ilist.begin(); iter != ilist.end(); ++iter, --i) {
cout << *iter;
if (i != 1)
cout << ", ";
}

cout << "}" << endl;

cout << "\nPress any key to exit..." << endl;
getch();
return 0;
}
回复 点赞
发动态
发帖子
C++ 语言
创建于2007-09-28

3.1w+

社区成员

24.8w+

社区内容

C++ 语言相关问题讨论,技术干货分享
社区公告
暂无公告