您好,欢迎来到二三娱乐。
搜索
您的当前位置:首页C++ STL练手(list的使用)

C++ STL练手(list的使用)

来源:二三娱乐
#include <list>  
#include <iostream>  
#include <algorithm>  
using namespace std;

void print(int num)
{
    cout << num << " ";
}

bool IsOdd(int i)
{
    return ((i & 1) == 1);
}

int main()
{
    //1. 初始化  
    list<int> v;
    list<int>::iterator iv;

    v.assign(10, 2);//将10个值为2的元素赋到list中  
    cout << v.size() << endl; //返回list实际含有的元素数量  
    cout << endl;

    //2. 添加  
    v.push_front(666);
    for (int i = 0; i < 10; i++)
        v.push_back(i);
    for_each(v.begin(), v.end(), print);//需要#include <algorithm>  
    cout << endl;
    cout << v.size() << endl;
    cout << endl;

    //3. 插入及遍历、逆遍历和倒转  
    v.insert(v.begin(), 99);//不能+和-了  
    v.insert(v.end(), 99);

    for_each(v.begin(), v.end(), print);
    cout << endl;
    for_each(v.rbegin(), v.rend(), print);//在逆序迭代器上做++运算将指向容器中的前一个元素  
    cout << endl;

    //一般遍历写法  
    for (iv = v.begin(); iv != v.end(); ++iv)
        cout << *iv << " ";
    cout << endl;

    v.reverse();
    for_each(v.begin(), v.end(), print);
    cout << endl;
    for_each(v.rbegin(), v.rend(), print);
    cout << endl;
    cout << endl;

    //4. 排序  
    v.sort();//为链表排序,默认是升序。  
    for_each(v.begin(), v.end(), print);
    cout << endl;
    cout << endl;

    //5. 删除  
    v.erase(v.begin());
    for_each(v.begin(), v.end(), print);
    cout << endl;
    v.insert(v.begin(), 99);//还原  

    //删掉链表中所有重复的元素  
    v.unique();
    for_each(v.begin(), v.end(), print);
    cout << endl;

    //去掉所有含2的元素  
    v.remove(2);
    for_each(v.begin(), v.end(), print);
    cout << endl;

    //删掉所有奇数  
    v.remove_if(IsOdd);
    for_each(v.begin(), v.end(), print);
    cout << endl;

    v.pop_front();
    v.pop_back();
    for_each(v.begin(), v.end(), print);
    cout << endl;
    cout << endl;

    //6. 查询  
    cout << v.front() << endl;
    cout << v.back() << endl;

    //7. 清空  
    v.clear();
    cout << v.size() << endl;//0  
    for_each(v.begin(), v.end(), print); //已经clear,v.begin()==v.end(),不会有任何结果。  

    return 0;
}

Copyright © 2019- yule263.com 版权所有 湘ICP备2023023988号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务