目录
list的基本功能
list是对链表的封装,使得操作起来更加方便。
数组和链表的区别
数组是可以随机访问的,只要我给他具体的索引位置,就能找到这个值。而链表是不能随机访问的,只能按顺序链式访问,所以链表只能使用迭代器iterator。
函数名称 | 功能 |
push_back | 在尾部添加一个元素 |
pop_back | 在尾部删除一个元素 |
push_front | 在头部添加一个元素 |
pop_front | 在头部删除一个元素 |
clear | 清空所有元素 |
size | 返回元素的个数 |
front | 返回头元素 |
back | 返回尾元素 |
insert | 在中间插入元素 |
erase | 删除中间的元素 |
添加元素
#include "stdio.h"
#include "string.h"
#include "list"
#include "iostream"
using namespace std;
int main()
{
list<int> lst;
lst.push_back(1);
lst.push_front(3);
lst.push_front(2);
for(list<int>::iterator iter = lst.begin(); iter != lst.end(); iter++)
{
int& value = *iter;
printf("%d\n", value);
}
cout << "end" << endl;
return 0;
}
结果为:
删除操作
#include "stdio.h"
#include "string.h"
#include "list"
#include "iostream"
using namespace std;
int main()
{
list<int> lst;
lst.push_back(1);
lst.push_front(3);
lst.push_front(2);
for(list<int>::iterator iter = lst.begin(); iter != lst.end(); iter++)
{
int& value = *iter;
if(value == 3)
{
lst.erase(iter);
break;
}
}
for(list<int>::iterator iter = lst.begin(); iter != lst.end(); iter++)
{
int& value = *iter;
printf("%d\n", value);
}
cout << "end" << endl;
return 0;
}
结果为:
结果中可以看出3被删除了。
自建对象使用list
#include "stdio.h"
#include "string.h"
#include "list"
#include "iostream"
using namespace std;
class Object
{
public:
Object(int id, const char* name)
{
this->id = id;
strcpy(this->name, name);
}
public:
int id;
char name[32];
};
int main()
{
list<Object> lst;
lst.push_back(Object(1, "a"));
lst.push_back(Object(2, "b"));
lst.push_back(Object(3, "c"));
/*
for(list<int>::iterator iter = lst.begin(); iter != lst.end(); iter++)
{
int& value = *iter;
printf("%d\n", value);
}
*/
for(list<Object>::iterator iter = lst.begin(); iter != lst.end(); iter++)
{
Object& value = *iter;
printf("%d, %s\n", value.id, value.name);
}
cout << "end" << endl;
return 0;
}
结果为: