STL:list用法總結

蝸牛201發表於2018-10-26

一:介紹

list底層為連結串列,非連續記憶體,不支援[]操作符,支援任意位置的插入操作。

名稱空間為std,所屬標頭檔案為<list>

二:常用操作

容量:
a.元素個數:list.size()
b.判斷是否為空:list.empty()

修改:
a.尾部新增元素:list.push_buack()
b.首部新增元素:list.push_front()
c.刪除尾部元素:list.pop_back()
d.刪除首部元素:list.pop_front()
e.插入1:list.insert(pos, num) 在pos位置插入元素num
f.插入2:list.insert(pos, n, num) 在pos位置插入n個元素num
g.插入3: list.insert(pos, beg, end) 在pos位置插入另外一塊起始位beg到end的元素

迭代器:
a.list.begin() 指向連結串列第一個元素的迭代器
b.list.end() 指向連結串列最後一個元素之後的迭代器

訪問:
a.訪問第一個元素:list.front()
b.訪問最後一個元素:list.back()

刪除:
a.清空:list.clear()
b.刪除指定元素:list.erase(it)

三:儲存

 1     //簡單儲存
 2     list<int> iList;
 3     iList.push_back(2);        //尾部新增
 4     iList.push_back(3);
 5     iList.push_front(1);    //首部新增
 6 
 7     //儲存結構體
 8     list<Student> stuList;
 9     Student stu1;
10     strcpy(stu1.name, "woniu201");
11     stu1.age = 30;
12     Student stu2;
13     strcpy(stu2.name, "beijing");
14     stu2.age = 30;
15     stuList.push_back(stu1);
16     stuList.push_back(stu2);

四:遍歷

1     for (list<Student>::iterator it = stuList.begin(); it != stuList.end(); it++)
2     {
3         cout << "name:" << it->name << endl;
4         cout << "age: " << it->age << endl;
5     }

五:排序

 1     //升序排序1
 2     iList.sort(less<int>());
 3     for (list<int>::iterator it = iList.begin(); it != iList.end(); it++)
 4     {
 5         cout << *it << endl;
 6     }
 7 
 8     //升序排序2
 9     iList.sort(compare1);
10     for (list<int>::iterator it = iList.begin(); it != iList.end(); it++)
11     {
12         cout << *it << endl;
13     }
14 
15     //降序排序1
16     iList.sort(greater<int>());
17     for (list<int>::iterator it = iList.begin(); it != iList.end(); it++)
18     {
19         cout << *it << endl;
20     }
21 
22     //降序排序2
23     iList.sort(compare2);
24     for (list<int>::iterator it = iList.begin(); it != iList.end(); it++)
25     {
26         cout << *it << endl;
27     }

六:查詢

1     list<int>::iterator it = find(iList.begin(), iList.end(), 2);
2     if (it == iList.end())
3     {
4         cout << "not found" << endl;
5     }
6     else
7     {
8         cout << "found"  << endl;
9     }

七:刪除

 1     for (list<int>::iterator it = iList.begin(); it != iList.end(); it++)
 2     {
 3         if (*it == 2)
 4         {
 5             it = iList.erase(it);
 6             it--;
 7         }
 8     }
 9     for (list<int>::iterator it = iList.begin(); it != iList.end(); it++)
10     {
11         cout << *it << endl;
12     }

 

掃碼關注公眾號

專注分享Java,C/C++,STL,Spring框架,mybatis框架,mysql,redis,分散式,高併發,設計模式,爬蟲,docker,shell程式設計等相關技術,在這裡一起探討,一起學習,一起進步,不定期分享視訊書籍資源,充分利用碎片化時間,讓我們的技術之路更加有樂趣。