16.7.4【列表list容器的数据存取、反转和排序】

#include<iostream>
#include<cstdlib>
using namespace std;
#include <list>
#include<algorithm>


/*
    3.7.6 list容器数据存取

        front(); //返回第一个元素。
        back(); //返回最后一个元素。

    3.7.7 list容器反转和排序

        reverse(); //反转链表
        sort(); //链表排序
*/


void print_list(const list<int> & L)
{
    for(list<int>::const_iterator cit=L.begin(); cit!=L.end(); cit++)
    {
        cout << *cit << " ";
    }
    cout << endl;
}


void test376()
{
    list<int> l1;
    l1.push_back(10);
    l1.push_back(20);
    l1.push_back(30);
    l1.push_back(40);

    //l1[0];
    //l1.at(0);
    //不可以用[]或at()直接访问list容器中的元素。原因是list本质是链表,而不是用连续线性空间存储数据,迭代器不支持随机访问。

    cout << "first:" << l1.front() << endl;
    cout << "last:" << l1.back() << endl;

    /*
    list<int>::iterator it = l1.begin();

    //支持双向
    it++; //前向OK,
    it--; //后向OK

    //但不支持随机访问
    //it = it + 1; //error
    //it += 3; //error
    */
}


void test377_1()
{
    list<int> l1;

    l1.push_back(20);
    l1.push_back(50);
    l1.push_back(10);
    l1.push_back(30);
    l1.push_back(40);

    cout << "翻转前:" << endl;
    print_list(l1);

    l1.reverse();

    cout << "翻转后:" << endl;
    print_list(l1);
}


bool my_compare(int num1, int num2)
{
    //降序:令 前一个数 > 后一个数
    return num1 > num2;
}


void test377_2()
{
    list<int> l1;
    l1.push_back(20);
    l1.push_back(50);
    l1.push_back(10);
    l1.push_back(30);
    l1.push_back(40);
    list<int> l2;
    l2 = l1;

    cout << "排序前:" << endl;
    print_list(l1);

    //sort(l1.begin(), l1.end()); //error
    //所有不支持随机访问迭代器的容器,不可以使用标准算法库的算法
    //但,这些不支持随机访问迭代器的容器,自己内部会提供一些对应功能的算法

    l1.sort(); //ok 默认升序
    cout << "排序后:" << endl;
    print_list(l1);


    cout << "排序前:" << endl;
    print_list(l2);
    l2.sort(my_compare); //利用回调函数或仿函数实现降序(此处为回调函数)
    cout << "排序后:" << endl;
    print_list(l2);
}


int main()
{
    test376();
    test377_1();
    test377_2();

    system("pause");
    return 0;
}

  

 

posted @ 2021-05-11 17:29  yub4by  阅读(104)  评论(0)    收藏  举报