STL编程 —— List

List (双向链表) 是一个线性链表结构,它的数据由若干个节点构成,每一个节点都包括一个信息块(实际存储的数据)、一个前驱指针和一个后驱指针。 它无需分配指定的内存大小且可以任意收缩,这是因为它存储在非联系的内存空间中,并且由指针将有序的元素连接起来。


测试代码1:

#include "iostream"
#include "list"
using namespace std;

void main()
{
	list<int> l;
	cout << l.size() << endl;
	for (int i = 0; i < 5; i++)
	{
		l.push_back(i + 1);
	}

	//取出元素
	cout << l.size() << endl;
	//返回一个迭代器
	list<int>::iterator current = l.begin();

	while (current != l.end())
	{
		cout << *current << "   ";
		current++;
	}
	cout << endl;
	system("pause");
}
测试代码2

#include "iostream"
#include "list"
using namespace std;


void main()
{
	list<int> l;

	cout << l.size() << endl;

	for (int i = 0; i < 5; i++)
	{
		l.push_back(i + 1);
	}

	//取出元素
	cout << l.size() << endl;
	//返回一个迭代器
	//定位开始位置
	list<int>::iterator current = l.begin();
	
	current++;
	current++;
	current++;

	l.insert(current, 100);

	for (list<int>::iterator p = l.begin(); p != l.end(); p++)
	{
		cout << *p << "  ";
	}
	cout << endl;
	system("pause");
}

测试代码3:

#include "iostream"
#include "list"
using namespace std;

struct Teacher
{
	char name[64];
	int age;
};

void main()
{
	list<Teacher> l;
	Teacher t1, t2,t3;
	t1.age = 11;
	t2.age = 22;
	t3.age = 33;

	l.push_back(t1);
	l.push_back(t2);
	l.push_back(t3);

	//l<Teacher>::iterator cur = l.begin();
	for (list<Teacher>::iterator cur = l.begin(); cur != l.end(); cur++)
	{
		Teacher tmp = *cur;
		cout << tmp.age << "  ";
	}
	cout << endl;


	system("pause");
}

测试代码4:

#include "iostream"
#include "list"
using namespace std;

struct Teacher
{
	char name[64];
	int age;
};

void main()
{
	list<Teacher *> l;
	Teacher t1, t2,t3;
	t1.age = 11;
	t2.age = 22;
	t3.age = 33;

	l.push_back(&t1);
	l.push_back(&t2);
	l.push_back(&t3);

	//l<Teacher>::iterator cur = l.begin();
	for (list<Teacher *>::iterator cur = l.begin(); cur != l.end(); cur++)
	{
		//Teacher *tmp = *cur;
		cout << (*cur)->age<< "  ";
	}
	cout << endl;
	system("pause");
}






原文链接: STL编程 —— List 版权所有,转载时请注明出处,违者必究。
注明出处格式:流沙团 ( http://www.gyarmy.com/post-11.html )

发表评论

0则评论给“STL编程 —— List”