STL之list

  • list的构造函数和其他的vector的容器差不多

  • list的赋值和交换和操作和vector容器差不多
  • list的插入与删除

  • 链表的数据存取
  • #include<iostream>
    using namespace std;
    #include<list>
    
    int main(void)
    {
        list<int> v;
    
        for (int i = 0; i < 10; i++)
        {
            v.push_back(i);
        }
    
        //v.at(0)和v[0]都不能访问list容器
        //原因是list的本质是链表,不是用连续线性空间存储数据,迭代器也是不支持随机访问的
    
        cout << "第一个元素" << v.front() << endl;
        cout << "最后一个元素为:" << v.back() << endl;
    
        //验证迭代器是不支持随机访问的
        list<int>::iterator it = v.begin();
        it++;
        it--;
        //但it = it +1 是不可以用的,因为list是链表不支持跳转
        return 0;
    }

     list的反转与排序

  • #include<iostream>
    using namespace std;
    #include<list>
    
    void myprint(const list<int> v)
    {
        for (list<int>::const_iterator it = v.begin(); it != v.end(); it++)
            cout << *it << " ";
        return;
    }
    
    bool cmp(int val1, int val2)
    {
        return val1 > val2;
    }
    
    int main(void)
    {
        list <int> L;
        L.push_back(19);
        L.push_back(29);
        L.push_back(9);
        L.push_back(35);
        L.push_back(25);
    
        L.reverse(); //反转函数,将容器内数值顺序反转
    
        myprint(L);
        cout << endl;
        L.sort();//默认升序排序
    
        myprint(L);
    
        L.sort(cmp);//使用谓词来改变排序规则
    
        myprint(L);
        return 0;
    }

     

posted @ 2020-12-18 22:35  loliconsk  阅读(33)  评论(0)    收藏  举报