前言
表(List)和栈(Stack)是最基础最简单的数据结构,为此,C++提供了现成的库(std::list与std::stack),其使用方法也比较简便。
简介
list和stack在头文件中分别定义为:
template<
class T,
class Allocator = std::allocator<T>
> class list;
以及
template<
class T,
class Container = std::deque<T>
> class stack;
list能够支持任意位置的快速插入删除(链表的特点),同时,它被实现为双向的。stack则是一个后进先出(先进后出)的表。
List
List的常用函数:
- front():访问首元素
- back():访问末元素
- empty():检查是否为空
- size():返回元素个数
- clear():删除全部内容
- insert():插入元素
- erase():删除元素
- push_back():将元素添加到末尾
- pop_back():删除末尾元素
- push_front ():将元素插入于首位
- pop_front():删除首位元素
unique():删除连续重复的元素
值得注意的几点:
erase不仅可以删除某一元素,还可以移除一定范围(一个区间内)的元素。其函数原型为:iterator erase( iterator first, iterator last );
- insert()的参数比较复杂,常见的iterator insert( iterator pos, const T& value );形式,实际上是插入到现有的这个位置(iterator)之前
代码
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <list>
using namespace std;
int main()
{
list<int> li;
list<int>::iterator it1,it2;
for (int i = 1; i < 10; i++) {
li.push_back(i); // new element will be in the last position
}
while (!li.empty()) {
cout<<li.front()<<" ";
li.pop_front(); // delete element in the first position
}
cout<<endl<<"Size: "<<li.size()<<endl; // size should be 0
for (int i = 0; i < 15; i++) {
li.push_back(i); // new element will be in the last position
}
it1 = ++li.begin(); // it will be the second position
it2 = --li.end(); // it will be the last but one
li.insert(it1,100);
li.insert(it1,100);
li.insert(it2,214);
li.insert(it2,214);
cout<<"Size: "<<li.size()<<endl; // size should be 19
for (list<int>::iterator it = li.begin(); it != li.end(); it++) {
cout<<*it<<" ";
}
cout<<endl;
li.unique();
for (list<int>::iterator it = li.begin(); it != li.end(); it++) {
cout<<*it<<" "; // get the elements
}
cout<<endl;
li.clear();
cout<<li.size()<<endl;
}
测试结果
参考资料
http://en.cppreference.com/w/cpp/container/list
http://www.cnblogs.com/fangyukuan/archive/2010/09/21/1832364.html