• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

c# 搞代码 4年前 (2022-01-09) 22次浏览 已收录 0个评论

这篇文章主本文来源gaodaimacom搞#^代%!码网@要介绍了C++中 STL list详解及简单实例的相关资料,需要的朋友可以参考下

C++中 STL list详解

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

2.、示例程序:

#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使用方法实例的详细内容,更多请关注搞代码gaodaima其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:C++中 STL list使用方法实例

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址