表的简单实现——使用C++容器库(STL List)

前言

表(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;
}

测试结果

List

参考资料

http://en.cppreference.com/w/cpp/container/list
http://www.cnblogs.com/fangyukuan/archive/2010/09/21/1832364.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值