容器
容器用于存放数据;STL的容器分为两大类:
- 序列式容器(Sequence Containers)
- 关联式容器(Associative Containers)
- 哈希容器
序列式容器(Sequence Containers)
其中的元素都是可排序的(ordered),STL提供了vector,list,deque
等序列式容器,而stack, queue, priority_quceue
则是容器适配器。
#include <vector>
#include <list>
#include <queue>
#include <iostream>
#include <stack>
#include <map>
#include <algorithm>
using namespace std;
struct Display
{
void operator()(int i)
{
cout << i << " ";
}
};
int main()
{
int iarr[] = { 1,2,3,4,5 };
vector<int> ivector(iarr, iarr + 4);
list<int> ilist(iarr, iarr + 4);
deque<int> ideque(iarr, iarr + 4);
queue<int> iqueue(ideque); // 队列 先进先出
stack<int> istack(ideque);
priority_queue<int> ipriority(iarr, iarr + 4);
for_each(ivector.begin(), ivector.end(), display());
cout << endl;
for_each(ilist.begin(), ilist.end(), display());
cout << endl;
for_each(ideque.begin(), ideque.end(), display());
cout << endl;
while (!iqueue.empty())
{
cout << iqueue.front() << " ";
iqueue.pop();
}
cout << endl;
while (!istack.empty())
{
cout << istack.top() << " ";
istack.pop();
}
cout << endl;
while (!ipriority.empty())
{
cout << ipriority.top() << " ";
ipriority.pop();
}
cout << endl;
return 0;
}
关联式容器(Associative Containers)
每个数据元素都是由一个键(key)和值(Value)组成,当元素被插入到容器时,按其键以某种特定规则放入适当位置;常见的STL关联容器。
如:set,multiset,map,multimap;
#include <vector>
#include <list>
#include <queue>
#include <iostream>
#include <stack>
#include <map>
#include <algorithm>
using namespace std;
struct Display1
{
void operator()(pair<string, double> info)
{
cout << info.first <<":"<< info.second << endl;
}
};
struct StuScore
{
string name;
double score;
};
int main()
{
map<string, double> studentSocres;
studentSocres["LiMing"] = 95.0;
studentSocres["LiHong"] = 95.0;
studentSocres.insert(pair<string, double>("zhangsan", 10.34));
studentSocres.insert(map<string, double>::value_type("wangwu", 49.54));
studentSocres.insert(map<string, double>::value_type("zhaoliu", 96.5));
studentSocres["wangwu"] = 85.5;
for_each(studentSocres.begin(), studentSocres.end(), Display1());
//vector< StuScore> studentSocres2;
//studentSocres2.push_back(StuScore());
map<string, double>::iterator iter;
iter = studentSocres.find("wangwu");
if (iter != studentSocres.end())
{
cout << "分数:" << iter->second << endl;
}
else
{
cout << "没有找到" << endl;
}
//使用迭代器完成遍历查找的过程
iter = studentSocres.begin();
while (iter != studentSocres.end())
{
if(iter->second < 95.0)
{
studentSocres.erase(iter++); //注意迭代器失效问题
}
else
{
iter++;
}
}
for_each(studentSocres.begin(), studentSocres.end(), Display1());
cout << endl;
return 0;
}
哈希容器
C++ 11 新加入 4 种关联式容器,分别是 unordered_set 哈希集合、unordered_multiset 哈希多重集合、unordered_map 哈希映射以及 unordered_multimap
哈希多重映射。和排序容器不同,哈希容器中的元素是未排序的,元素的位置由哈希函数确定。
注意,由于哈希容器直到 C++ 11 才被正式纳入 C++ 标准程序库,而在此之前,“民间”流传着 hash_set、hash_multiset、hash_map、hash_multimap 版本,不过该版本只能在某些支持 C++ 11 的编译器下使用(如 VS),有些编译器(如 gcc/g++)是不支持的。