MFC ,List使用


 List容器
雙向線性表list容器
   list類定義了雙向的線性表。Vector類支持隨機訪問,但list只能支持順序訪問,由於list是雙向的,因此我們可以按從前到后或者從后到前的順序來訪問list。
1.創建一個list對象
#include<list>
using namespace std;
    
list<int> lst1;
list<char> lst2;
2.向list對象中添加數值
從前面添加:
         lst1.push_front(0);
         lst1.push_front(1);
從后面添加:
   lst1.push_back(0);
         lst1.push_back(1);
3.刪除操作
刪除list對象中的第一個元素
  lst1.pop_front();
刪除list對象中的最后一個元素
  lst1.pop_back();
4.獲得list對象的存儲容量
 lst1.size();
5.獲得list對象中第一個和最后一個元素
 list<int>::iterator p = lst1.begin();
        list<int>::iterator p = lst1.end();
6.在list對象中插入元素
        list<int>::iterator p = lst1.begin();
        p++;
        lst1.insert(p, 2 , 100);
7.在list對象中刪除元素;
 list<int>::iterator p1 = lst1.begin();
        list<int>::iterator p2 = lst1.begin();
        for (i=0;i<5;i++) p2++;
        lst1.erase(p1, p2);
8.訪問list對象中的內容
 list<int>::iterator p = lst1.begin();
        while (p!=lst1.end())
 {
        *p = *p + 100;
         p++;
        }
9.將list對象中的內容排序;
 lst1.sort();

 

 

 

list應用問題

要求使用list解題
    輸入:第一個行為總組數,從第二行開始為每組數,每組數的第一個數為該組數的個數。
    輸出:將所有組的數排序無重復輸出。
    輸入
    2
    3
    3
    4
    5
    5
    1
    2
    3
    4
    5
    輸出
    1 
    2
    3
    4
    5

 

 

程序源碼:

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

int main()
{
 //定義一個整型的list對象lst
 list<int> lst;
 int i;
 
 //往lst頭和尾插入整數
 lst.push_front(10);
 lst.push_front(20);
 lst.push_front(30);
    lst.push_back(1);
 lst.push_back(2);
 lst.push_back(3);

    for (i=0; i<=10;i++)  lst.push_back(i);

 //輸出lst中的所有元素
 //定義一個迭代器p
 list<int>::iterator p = lst.begin();
 while (p!=lst.end())
 {
  cout << *p << "  ";
  p++;
 }
 cout << endl;
 
 //將lst中的元素排序
 lst.sort();

 p = lst.begin();
 while (p!=lst.end())
 {
  cout << *p << "  ";
  p++;
 }
 cout << endl;

 //刪除lst中的重復元素
 lst.unique();
 
 p = lst.begin();
 while (p!=lst.end())
 {
  cout << *p << "  ";
  p++;
 }
 cout << endl;

 return 0;

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM