zoukankan      html  css  js  c++  java
  • list 函数

    * 23-12-10 19:49
    熟悉链表的库函数操作:创建链表,插入元素,删除元素,查找元素,为链表排序 遍历元素 掌握其使用 
    这里用模板实现 
    */
    #include <iostream>
    #include <list>      //链表头文件 
    #include <algorithm> //find函数头文件 
    using namespace std;
    
    int main()
    {
    list<int>   L;
    list<int>::iterator it;
    
    //插入元素 输出
       int i=0,n;  //插入数量 
       int num; 
       cout<<"输入要插入元素的个数:";
       cin>>n;
       cout<<"输入"<<n<<"个元素:"<<endl; 
       while (i<n)
       {
          cin>>num;
          L.push_back(num);   //重尾部插入元素 这样可以保证元素的顺序正确 
          i++;
       } 
       //输出 
       for (it=L.begin(); it!=L.end(); it++)
       {
             cout<<*it<<" ";
       }
       cout<<endl;
       
       //查找元素 
       int searh;
       cout<<"输入要找的元素:";
    cin>>searh;
    it = find(L.begin(), L.end(), searh);
    if (it!=L.end())
    {
    cout<<searh<<"查找成功"<<endl;
    }
    else
    {
    cout<<"查找失败"<<endl;
    }
    
    //排序
    L.sort();
    //输出 
    cout<<"排好序后的元素为:"<<endl;
       for (it=L.begin(); it!=L.end(); it++)
       {
             cout<<*it<<" ";
       }
       cout<<endl;
       
       //删除元素 
       int k = 0;
       int de; 
    cout<<"输入要删除第几个元素:";
    cin>>de;
    while (k!=de)
    {
    it++;
    k++;
    }
    L.erase(it);   //删除元素  remove函数也行,相同元素一起删除
    cout<<"删除后的元素为:"<<endl;
       for (it=L.begin(); it!=L.end(); it++)
       {
             cout<<*it<<" ";
       }
       cout<<endl;
    
    //插入元素 
    int inser,m,h=0;
    cout<<"输入要插入的元素:";
    cin>>inser;
    cout<<"输入要插入的位置:";
    cin>>m;
    
    while (h!=m)
    {
    it++;
    h++;
    }
    //插入元素
    L.insert(it, inser);  //在it位置插入num
    
    cout<<"插入后的元素为:"<<endl;
       for (it=L.begin(); it!=L.end(); it++)
       {
             cout<<*it<<" ";
       }
       cout<<endl;
       
    
        system("pause");
        return 0;
    }
    
  • 相关阅读:
    原生态 php连接mysql
    sql查询慢 查找
    死锁查询和处理
    linq详细案例
    linq深入
    DataTable 与XML 交互
    DataTable运用
    通过反射修改已有数组的大小
    通过反射取得并修改数组信息
    通过反射机制直接操作属性
  • 原文地址:https://www.cnblogs.com/zhangdongdong/p/3022841.html
Copyright © 2011-2022 走看看