STL常用容器简介
1:相同点
@1:用法一样的成员函数
- c.clear() 移除容器中所有数据。
- c.empty() 判断容器是否为空。
- c.erase(pos) 删除pos位置的数据
- c.erase(beg,end) 删除[beg,end)区间的数据
- c.front() 传回第一个数据。
- c.pop_back() 删除最后一个数据。
- c.push_back(elem) 在尾部加入一个数据。
- c.size() 回容器中实际数据的个数。
- c.begin() 返回指向容器第一个元素的迭代器
- c.end() 返回指向容器最后一个元素的迭代器
2:差异点
3:set集合
2:常用成员函数
1.元素插入: insert(a)
2.中序遍历:std::set<int>::interator it;
3.反向遍历: 利用反向迭代器 std::set<int>::reverse_interator it;
3:使用方法
#include<set>
struct INFO
{ }; //结果体
void main()
{
std::set<INFO> setInfo;
INFO info1;
/*插入*/
setInfo.insert(info1);
/*删除*/
setInfo.erase(info1);
/*查找*/
std::set<INFO>::interator it = setInfo.find(info1);
if (it != setInfo.end) {} //找到
}
4:注意点
//存储结构体时需要 重载运算符 <
struct dPoint
{
double x;
double y;
//重载"<"关系运算符,犹豫set容器只用到小于比较,其他几个可以不管
bool operator<(const dPoint& point) const
{
if(x != point.x)
return (x < point.x);
else
return (y < point.y);
}
//为了方便读取,可以重载一下赋值运算符
dPoint& operator=(const dPoint& point)
{
this->x = point.x;
this->y = point.y;
return *this;
}
};
4:map
1:简介
通过索引查找->叫关联容器
std::map<std::string,int> mapTest; map<key,对象>
2:常用成员函数:
mapTest.insert(std::map<int, std::string>value_type(2,"valuse"));
mapTest.insert(pair<int, std::string>(3,"aclive"));
mapTest[key] = values; //可以如数组的方式插入。 key可以是字符串 。
{ int nValues = mapTest[key];可以这样获取值,但是这样不建议最好不要。}
3:使用方法
#include <map>
#include<string>
struct INFO
{ } //结果体
void main()
{
//用int作为索引(key),存储string对象
map<int, std::string> mapTest;
//插入
mapTest.insert(std::map<int, std::string>value_type(2,"valuse"));
mapTest.insert(pair<int, std::string>(3,"aclive"));
//查找指定
std::map<std::string,int>::iterator it = mapTest.find(key);
if(it!=mapTest.end()){
return it->second; //对象 it->first;key值
}
}
4:注意点
5:vector向量
1:简介
vector 向量容器--------相当于动态数组
list<int> Link 同向量一样只是,插入删除速度比较快点(一般使用vector就可以了)
2;常用成员函数
c.insert(pos,elem) 在pos位置插入一个elem拷贝
c.resize(num) 重新设置该容器的大小
c.resize(num) 重新设置该容器的大小
int nValues = c[size]; //可以这样获取值
3:使用方法
#include<vector>
using namespace std;
struct INFO //结构体
{ };
void main()
{
//定义一个没有指定大小的数组
vector<INFO> vec;
INFO info1;
//在尾部插入
vec.push_back(info1);
//删除指定
vector<INFO>::interator it = vec.begin();
while(it != vec.end())
{
if (*it == info1)
{
vec.erase(it);
continue; //删除成功后自动指向下一个
}
else
it++;
}
}
6:deque 队列
1:使用
//使用方法
#include <deque>
using namespace std;
void main()
{
deque<int> deqIdle;
deqIdle.push_back(1); // 在尾部加入一个数据
deqIdle.push_front(2); // 在头部加入一个数据
int nNUm = deqIdle.front(); //传回第一个数据。
}
7:什么是STL
1:STL 是标准模板库2:STL的六大组件1:容器:是一种数据结构,入vector ,以模板类的方法提供,为了访问容器中的数据,可以使用由容 器输出的迭代器。2:迭代器(iterstor)提供了访问容器中对象的方法1:迭代器模式 又称为 Cursor(游标)模式,用来提供一种方法顺序访问一个聚合对象中的各个元素,而又不暴露该对象内部表示,{就是我们可以在不知道对象内部表示情况下,按照一定顺序访问聚合对象中的各个元素}2:作用:为了让迭代器和算法不互相干扰发展,最后又能无缝粘合,重载了 *,++,==,!=,= 运算符。3:算法是用来操作容器中的数据模板函数,入STL用sort() 排序。4:仿函数又称函数对象,其实就是重载了()操作符的struct5:迭代适配器6:空间配置器主要工作是:1:对象的创建与摧毁 2:内存的获取和释放。