注册 登录
编程论坛 C++教室

一个关于C++中list的问题

lxqlyld 发布于 2012-07-12 17:03, 399 次点击
请问各位高手,怎样将链表list中的内容用cout输出以及怎样访问list中的内容,最好帮举个例子,非常感谢啊
我的这个问题是我在做一个习题时遇到的:
int ia[] = { 0, 1, 1, 2, 3, 5, 8, 13, 21, 55, 89 };
list<int> ilist( ia, ia+11 );
用单个iterator 形式的erase()删除ilist 中所有奇数位置的元素。
程序写到最后,不知道该怎么访问ilist中的元素,卡住了

[ 本帖最后由 lxqlyld 于 2012-7-13 09:06 编辑 ]
4 回复
#2
peach54602012-07-12 20:02
list只是一个链表而已

比如说
std::list<int> listInt;
listInt.push_back(1);
listInt.push_back(2);
listInt.push_back(3);

for(std::list<int>::iterater itr = listInt.begin(); itr != listInt.end(); ++itr)
{
cout << *itr;
}
#3
lxqlyld2012-07-13 09:05
回复 2楼 peach5460
这样的输出好像是不对的,我在书上看到,iterator 算术运算只适用于vector 或deque, 而不适用于list ,因为list 的元素在内存中不
是连续存储的,例如
ilist.begin() + 2;是错误的。
#4
peach54602012-07-13 10:58
程序代码:

void Test21()
{
    std::list<int> listInt;
    listInt.push_back(1);
    listInt.push_back(2);
    listInt.push_back(3);

    for (std::list<int>::iterator itr = listInt.begin(); itr != listInt.end(); ++itr)
    {
        cout << *itr << endl;
    }
}


以上代码在VS2008中编译通过,运行正确

STL连联表基本算法都搞不定就白活啦
#5
rjsp2012-07-13 13:41
回复 3楼 lxqlyld
peach5460 说得是正确的

程序代码:
#include <iostream>
#include <iterator>
#include <list>
#include <algorithm>
using namespace std;

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

    int i = 1;
    for( list<int>::iterator itor=ilist.begin(); itor!=ilist.end(); ++i )
    {
        if( i&1 )
            itor = ilist.erase( itor );
        else
            ++itor;
    }

    copy( ilist.begin(), ilist.end(), ostream_iterator<int>(cout,", ") );
    cout << endl;

    return 0;
}

输出
1, 2, 5, 13, 55,
1