C++中 STL list使用方法实例


本文摘自PHP中文网,作者PHPzhong,侵删。

这篇文章主要介绍了C++中 STL list详解及简单实例的相关资料,需要的朋友可以参考下

C++中 STL list详解

1、List: 内部实现是一个双向链表,可以高效的进行插入删除,但不能够进行随机访问

2.、示例程序:


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

#include "stdafx.h"

#include <iostream>

#include <list>

#include <iterator>

#include <algorithm>

using namespace std;

const int num[5] = {1,3,2,4,5};

bool status(const int & value)

{

 return value>6?true:false;

}

int _tmain(int argc, _TCHAR* argv[])

{

 list<int> list1;

 copy(num,num+5,back_insert_iterator<list<int>>(list1));

 copy(list1.begin(),list1.end(),ostream_iterator<int>(cout," "));

 cout<<endl;

 list1.sort(greater<int>());//5 4 3 2 1

 copy(list1.begin(),list1.end(),ostream_iterator<int>(cout," "));

 cout<<endl;

 list<int>::iterator it = list1.begin();

 while (it != list1.end())

 {

  (*it) += 2;

  it++;

 }

 //7 6 5 4 3

 list<int>::reverse_iterator re_it = list1.rbegin();

 cout<<"从后向前输出: ";

 while (re_it != list1.rend())

 {

  cout<<*re_it<<" ";

  re_it++;

 }

 cout<<endl;

 list1.reverse();// 3 4 5 6 7

 list1.push_back(8);//3 4 5 6 7 8

 list1.pop_front();//4 5 6 7 8

 list1.remove(6);//4 5 7 8

 list1.remove_if(status);// 4 5

 list1.resize(4);// 4 5 0 0

 list1.resize(6,1);// 4 5 0 0 1 1

 list1.unique();//4 5 0 1

 copy(list1.begin(),list1.end(),ostream_iterator<int>(cout," "));

 cout<<endl;

 list1.clear();

 cout<<"当前list1含有元素个数:"<<list1.size()<<endl;

 list1.push_back(7);//list1:7

 list<int> list2(3,2);//2 2 2

 list2.merge(list1,greater<int>());//list2: 7 2 2 2

 list2.insert(++list2.begin(),3);//list2: 7 3 2 2 2

 list2.swap(list1);//list1:7 3 2 2 2 list2:empty

 list1.erase(++list1.begin(),list1.end());// 7

 copy(list1.begin(),list1.end(),ostream_iterator<int>(cout," "));

 cout<<endl;

 system("pause");

}

运行结果图片:


3、List 方法

list成员

说明

constructor

构造函数

destructor

析构函数

operator=

赋值重载运算符

assign

分配值

front

返回第一个元素的引用

back

返回最后一元素的引用

begin

返回第一个元素的iterator

end

返回最后一个元素的下一位置的iterator

rbegin

返回链表最后一元素的后向指针reverse_iterator

rend

返回链表第一元素的下一位置的reverse_iterator

push_back

增加一个数据到链表尾

push_front

增加一个数据到链表头

pop_back

删除链表尾的一个元素

pop_front

删除链表头的一元素

clear

删除所有元素

erase

删除一个元素或一个区域的元素(两个重载)

remove

删除链表中匹配值的元素(匹配元素全部删除)

remove_if

删除条件满足的元素(遍历一次链表),参数为自定义的回调函数

empty

判断是否链表为空

max_size

返回链表最大可能长度

size

返回链表中元素个数

resize

重新定义链表长度(两重载函数)

reverse

反转链表

sort

对链表排序,默认升序

merge

合并两个有序链表并使之有序

splice

对两个链表进行结合(三个重载函数) 结合后第二个链表清空

insert

在指定位置插入一个或多个元素(三个重载函数)

swap

交换两个链表(两个重载)

unique

删除相邻重复元素

以上就是C++中 STL list使用方法实例的详细内容!

相关阅读 >>

c++中 STL list使用方法实例

更多相关阅读请进入《STL》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...