挑一些不熟的、使用频率低的STL写,备忘用
vector, stack, queue等使用频率比较高,就不写了
参考了网上的一些文章
欢迎在评论区提意见~
1.定义一个list
#include <string>
#include <list>
int main()
{
list<string> Milkshakes;
return 0;
}
2. 使用list的成员函数push_back()和push_front()插入一个元素到list中
#include <string>
#include <list>
int main (void)
{
list<string> Milkshakes;
Milkshakes.push_back("Chocolate");
Milkshakes.push_back("Strawberry");
Milkshakes.push_front("Lime");
Milkshakes.push_front("Vanilla");
return 0;
}
3.成员函数empty()
判断list是否为空
4.迭代器iterator
#include <iostream.h>
#include <string>
#include <list>
int main (void)
{
list<string> Milkshakes;
list<string>::iterator MilkshakeIterator;
Milkshakes.push_back("Chocolate");
Milkshakes.push_back("Strawberry");
Milkshakes.push_front("Lime");
Milkshakes.push_front("Vanilla");
// print the milkshakes
Milkshakes.push_front("The Milkshake Menu");
Milkshakes.push_back("*** Thats the end ***");
for (MilkshakeIterator=Milkshakes.begin(); MilkshakeIterator!=Milkshakes.end(); ++MilkshakeIterator)
{
// dereference the iterator to get the element
cout << *MilkshakeIterator << endl;
}
}
.begin()指向第一个元素,.end()指向最后一个元素的下一个位置,访问最后一个元素:.end()--list容器中不能使用
.begin()+2来访问第三个对象,因为STL的list是一双链的list来实现的,不支持随机存取。vector和deque和一些其他的容器支持随机存取5.使用STL的通用算法for_each()来遍历list
for_each()可以简化遍历工作#include <iostream>
#include <string>
#include <list>
#include <algorithm>
using namespace std;
void PrintIt(string& s)
{
cout << s << endl;
}
int main (void)
{
list<string> Milkshakes;
list<string>::iterator MilkshakeIterator;
Milkshakes.push_back("Chocolate");
Milkshakes.push_back("Strawberry");
Milkshakes.push_front("Lime");
Milkshakes.push_front("Vanilla");
// print the milkshakes
Milkshakes.push_front("The Milkshake Menu");
Milkshakes.push_back("*** Thats the end ***");
for_each(Milkshakes.begin(), Milkshakes.end(), PrintIt);
return 0;
}
对
[ begin() , end() )的中的每一个元素应用函数PrintIt6.使用成员函数sort()对list排序
这里使用的是list的成员函数
sort(),而不是通用算法sort()。STL中有时容器支持它自己对一个特殊算法的实现,这通常是为了提高性能。因为通用算法仅能为那些提供随机存取里面元素的容器排序,而由于list是作为一个连接的链表实现的,它不支持对它里面的元素随机存取。所以就需要一个特殊的
sort()成员函数来排序list。list1.sort();
默认升序
自定义比较函数
comp://定义结构体
typedef struct NewTreeElem
{
long nNodeId; //节点id
int nLevel; //层次
double dSoIn; //社会影响
};
//定义全局比较函数:
boolCompInfo(NewTreeElem first, NewTreeElem second)
{
if(first.dSoIn <= second.dSoIn) //由大到小排序
return false;
else
return true;
}
//定义链表: list<NewTreeElem> listSocialInf //链表排序: listSocialInf.sort(CompInfo);
7.使用list的成员函数inster()插入元素到list中
list1.insert(iterator, value); list1.insert(list1.begin(), "aaa");
注意,
insert()函数把一个或若干个元素插入到你指出的iterator的位置。你的元素将出现在 iterator指出的位置以前。8.删除list中的元素
a.使用成员函数
erase()
list1.erase(iterator); list1.erase(list1.begin());
b.使用STL通用算法
remove()
list1.remove(value);
list1.remove("aaa");
c.使用成员函数
pop_front() / pop_back()删除链首/尾元素
list1.pop_front();
9.使用STL通用算法find()判断是否存在某元素
listiter=find(listintegers.begin(),listintegers.end(),6); if(listiter==listintegers.end()) cout<<"6 is not in list"<<endl; else cout<<"6 is in list"<<endl;
若没有找到元素则返回
listintergers.end()的值