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 | 删除相邻重复元素 |
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!