前言
map的特性和set一样,就是他们都会自动的排序,其中map所有的元素都是pair,同时拥有实值和键值,第一个元素为实值,第二个为键值,map不允许有两个相同的元素
map和list有一些相似,就是他们中有删除现象出现的时候。不会影响迭代器,其实map和multimap的底层实现原理都是红黑树,multimap和map区别就是key可以重复
常用的接口
map构造函数
map<T1, T2> mapTT;//map默认构造函数:
map(const map &mp);//拷贝构造函数
map赋值操作
map& operator=(const map &mp);//重载等号操作符
swap(mp);//交换两个集合容器
map大小操作
size();//返回容器中元素的数目
empty();//判断容器是否为空
map插入数据元素操作
map.insert(...); //往容器插入元素,返回pair<iterator,bool>
map<int, string> mapStu;
// 第一种 通过pair的方式插入对象
mapStu.insert(pair<int, string>(3, "小张"));
// 第二种 通过pair的方式插入对象 //推荐
mapStu.inset(make_pair(-1, "校长"));
// 第三种 通过value_type的方式插入对象
mapStu.insert(map<int, string>::value_type(1, "小李"));
// 第四种 通过数组的方式插入值
mapStu[3] = "小刘";
mapStu[5] = "小王";
*/
map删除操作
clear();//删除所有元素
erase(pos);//删除pos迭代器所指的元素,返回下一个元素的迭代器。
erase(beg,end);//删除区间[beg,end)的所有元素 ,返回下一个元素的迭代器。
erase(keyElem);//删除容器中key为keyElem的对组。
map查找操作
find(key);//查找键key是否存在,若存在,返回该键的元素的迭代器;/若不存在,返回map.end();
count(keyElem);//返回容器中key为keyElem的对组个数。对map来说,要么是0,要么是1。对multimap来说,值可能大于1。
lower_bound(keyElem);//返回第一个key>=keyElem元素的迭代器。
upper_bound(keyElem);//返回第一个key>keyElem元素的迭代器。
equal_range(keyElem);//返回容器中key与keyElem相等的上下限的两个迭代器。
代码测试
void pri(map<int,int>&m)
{
for (map<int, int>::iterator it = m.begin(); it != m.end(); it++)
{
cout << "key = " << it->first << " " << "val = " << it->second << endl;
}
}
void test1()
{
//插入
map<int, int>m;
m.insert(make_pair(1, 10)); //推荐使用这种茶人方式
m.insert(make_pair(2, 10));
m.insert(make_pair(3, 10));
m.insert(make_pair(4, 10));
m.insert(make_pair(55, 10));
m.insert(make_pair(43, 10));
m.insert(make_pair(234, 10));
m.insert(make_pair(53, 10));
m.insert(pair<int, int>(0, 88));
//删除
map<int, int>::iterator pos = m.begin();
m.erase(pos);
//查找
pos=m.find(2);
if (pos == m.end())
cout << "未找到" << endl;
else
cout << "找到" << endl;
pair<map<int,int>::iterator ,map<int,int>::iterator > all =m.equal_range(43);
if (all.first != m.end())
{
cout << "key = " << all.first->first << " " << "val = " << all.first->second << endl;
}
else
cout << "上边为找到" << endl;
if (all.second != m.end())
{
cout << "key = " << all.second->first << " " << "val = " << all.second->second << endl;
}
else
cout << "下边为找到" << endl;
m.erase(4);
cout << "-------------------------" << endl;
pri(m);
}
int main()
{
test1();
std::cout << "Hello World!\n";
}
运行结果