zoukankan      html  css  js  c++  java
  • list基本使用

    list和vector的用法基本相同,区别如下:

    • list可以头尾插入和删除,效率一样,vector只有尾部插入和删除效率才高,头部操作效率很低

    • list的排序有专有的接口,不能使用全局的接口,原因是list中的节点不能随机访问,vector中的节点可以随机访问

    • vector是连续存储,list不是连续存储

    基本用法

    #include <iostream>
    #include <list>
    
    using namespace std;
    
    /*
        clear()            清空链表
        empty()         判断list是否为空
        size()             获取list中的元素个数 
        pop_back()         删除最后一个元素(效率高) 
        pop_front()     删除第一个元素(效率高) 
        push_back()     在list的末尾添加一个元素(效率高)  
        push_front()     在list的头部添加一个元素(效率高) 
        erase()         删除指定元素 
        sort()             排序
        reverse()        反转
    */
     
    int main()
    {
        list<int> l;
        
        l.push_back(1);
        l.push_back(4);
        l.push_front(3);
        l.push_front(2);
        
        cout << "size : " << l.size() << endl;
        
        l.sort(); // 特有排序接口
    
        reverse(l.begin(), l.end());
        
        // 4 3 2 1 
        for(list<int>::iterator it = l.begin(); it != l.end(); ++it)
        {
            cout << *it << ends;
        }
        cout << endl;
        
        l.clear();
        
        cout << "size : " << l.size() << endl;
    
        return 0;
    }    

    循环删除(类似vector)

    #include <iostream>
    #include <list>
    
    using namespace std;
     
    int main()
    {
        list<int> l;
        
        l.push_back(1);
        l.push_back(4);
        l.push_front(3);
        l.push_front(2);
        
        // 循环删除
        for(list<int>::iterator it = l.begin(); it != l.end();)
        {
            if(*it == 4)
            {
                it = l.erase(it);
            }
            else
            {
                ++it;
            }
        }
        
        // 2 3 1
        for(list<int>::iterator it = l.begin(); it != l.end(); ++it)
        {
            cout << *it <<ends;
        }
        cout << endl;
    
        return 0;
    }    
  • 相关阅读:
    rxjs 学习实践笔记
    封装localStorage、sessionStorage设置,获取,移除方法
    Angular实现类似vuex状态管理功能、全局数据管理与同步更新
    关于RxJS 处理多个Http请求 串行与并行方法
    vue插件汇总
    vue使用videojs控制后台m3u8数据请求
    NPOI winform读取Excel
    //邮件发送:
    定时任务框架Quartz.net
    系统日志控件 Log4NET
  • 原文地址:https://www.cnblogs.com/chusiyong/p/12849558.html
Copyright © 2011-2022 走看看