STL 线性容器 之 双端队列、列表

1. 双端队列和向量的差别

在这里插入图片描述

2. 列表

在任何位置添加、删除数据都很方便,但不支持下标访问
这里的列表就是之前这篇博客写的链表,下面利用<list>实现下几个那篇博客里没有实现的功能
在这里插入图片描述

  • unique : 针对的是连续重复出现的数据
  • 排序:
    • 之前那个全局的sort可以对链表进行的排序,只不过需要交换链表中数据的位置。
    • 在连续的数据存储区,进行数据的排序,必须要交换数据的位置。链表排序也可以交换数据的位置,但还有更简单的做法就是更改指针的指向。所有链表提供了两个自己的排序成员函数,并且没有卡范围,也就是整个链表的排序。
  • 拆分:
    • pos的作用就是将参数列表的元素剪切到调用列表当中,并保存到pos这个迭代器指向节点的前面。
#include <iostream>
#include <list>
#include <vector>
#include <cstdio>
#include <algorithm>     // find, sort 要用
using namespace std;

void print(string const& str, list<int> l){
    cout << str << endl;
    typedef list<int>::iterator IT;
    for(IT it = l.begin(); it != l.end(); it++){
        cout << *it << " ";
    }
    cout << endl << "---------------" << endl;
}

class CMP{
public:
    bool operator()(int const& a, int const& b){
        return a > b;   // > 降序排序,< 升序排序
    }
};

int main() {
    list<int> ls;
    for(int i=0; i<5; i++){
        ls.push_front(10+i);
    }
    for(int i=0; i<5; i++){
        ls.push_back(10-i);
    }
    print("添加元素以后: ", ls);

    ls.unique();
    print("唯一化以后:", ls);

    // 链表本身有sort成员函数,修改指针朝向,不交换数据位置,非常高效
    ls.sort();
    print("升序排列以后:", ls);
    // 还有比较器版本的
    CMP cmp;
    ls.sort(cmp);
    print("降序排列以后:", ls);

    list<int> lst;
    lst.push_back(1000);
    lst.push_back(2000);
    lst.push_back(3000);
    // 参数列表中的元素被剪切到调用链表当中
    // 剪切全部
    ls.splice(ls.begin(), lst);
    print("ls:", ls);
    print("lst:", lst);
    // // 剪切一个
    // ls.splice(ls.begin(), lst, lst.begin());
    // print("ls:", ls);
    // print("lst:", lst);
    // 剪切部分(略)
    return 0;
}
$ ./a.out 
添加元素以后: 
14 13 12 11 10 10 9 8 7 6 
---------------
唯一化以后:
14 13 12 11 10 9 8 7 6 
---------------
升序排列以后:
6 7 8 9 10 11 12 13 14 
---------------
降序排列以后:
14 13 12 11 10 9 8 7 6 
---------------
ls:
1000 2000 3000 14 13 12 11 10 9 8 7 6 
---------------
lst:

---------------
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值