C++笔记
一、vector 容器浅析
向量(Vector)是一个封装了动态大小数组的顺序容器(Sequence Container)。跟任意其它类型容器一样,它能够存放各种类型的对象。可以简单的认为,向量是一个能够存放任意类型的动态数组。
容器特性:
1.顺序序列
顺序容器中的元素按照严格的线性顺序排序。可以通过元素在序列中的位置访问对应的元素。
2.动态数组
支持对序列中的任意元素进行快速直接访问,甚至可以通过指针算述进行该操作。操供了在序列末尾相对快速地添加/删除元素的操作。
3.能够感知内存分配器的(Allocator-aware)
容器使用一个内存分配器对象来动态地处理它的存储需求。
vectorobj; //创建一个向量存储容器 int
obj.push_back(i); // 在数组最后添加数据
obj.pop_back(); //去掉数组最后一个数据
obj.clear();//清除容器中所以数据
sort(obj.begin(),obj.end());//从小到大
reverse(obj.begin(),obj.end());//从大到小
//顺序访问
vectorobj;
for(int i=0;i<10;i++)
{
obj.push_back(i);
}
//方法二,使用迭代器将容器中数据输出
vector::iterator it;//声明一个迭代器,来访问vector容器,作用:遍历或者指向vector容器的元素
for(it=obj.begin();it!=obj.end();it++)
{
cout<<*it<<" ";
}
unordered_map
网址:
https://blog.csdn.net/m0_38083668/article/details/81139706
#include<tr1/unordered_map>//在unordered_map之前加上tr1库名,
using namespace std::tr1;//与此同时需要加上命名空间 //[查找元素是否存在]
unordered_map<int, int> mp
if(mp.find(x)!=mp.end()) //方法一:查找x是否在map中
if(mp.count(x)!=0) //方法二:查找x是否在map中
//[插入数据]
mp[x] = 1; //使用[ ]进行单个插入,若已存在键值2,则赋值修改,若无则插入。
mp.insert(pair<int, int>(x, 1));//使用insert和pair插入
//[遍历map]
unordered_map<key,T>::iterator it;
(*it).first; //the key value
(*it).second //the mapped
valuefor(unordered_map<key,T>::iterator iter=mp.begin(); iter!=mp.end();iter++)
cout<<"key value is"<<iter->first<<" the mapped value is "<< iter->second;