总括
函数 | 功能 | 时间复杂度 |
---|---|---|
insert | 插入 | O(logn) |
erase(key) | 删除元素 | O(logn) |
find(key) | 查找 | O(logn) |
count(key) | 统计元素个数 | O(logn) |
size | 返回元素个数 | O(1) |
begin | 返回指向容器起始位置的迭代器 | O(1) |
end | 返回指向容器末尾位置的迭代器 | O(1) |
clear | 清空容器 | O(1) |
empty | 判断容器是否为空 | O(1) |
lower_bound | 返回第一个不小于指定键的元素位置 | O(logn) |
upper_bound | 返回第一个大于指定键的元素位置 | O(logn) |
key_comp() | 返回比较元素key的函数 | |
rbegin() | 返回一个指向map尾部的逆向迭代器 | |
rend() | 返回一个指向map头部的逆向迭代器 | |
swap() | 交换两个map | |
lower_bound() | 返回键值>=给定元素的第一个位置 | |
upper_bound() | 返回键值>给定元素的第一个位置 | |
value_comp() | 返回比较元素value的函数 |
事例
#include <bits/stdc++.h>
using namespace std;
int main()
{
map<int, string> map1 = { {1,"Apple"},{2,"Banana"},{3,"Orange"} };
//插入元素
map1.insert(make_pair(4, "Grapes"));
//查找和访问元素
cout << "Value at Key2: " << map1[2] << "\n";
//遍历并打印map中的元素
for (const auto& pair : map1) {
cout << "Key: " << pair.first << ", Value: " << pair.second << "\n";
}
//删除元素
map1.erase(3);
//判断元素是否存在
if (map1.count(3) == 0)
cout << "Key3 not found." << "\n";
//清空map
map1.clear();
//判断map是否为空
if (map1.empty())
cout << "map1 is empty." << "\n";
}
输出结果
Value at Key2: Banana
Key: 1, Value: Apple
Key: 2, Value: Banana
Key: 3, Value: Orange
Key: 4, Value: Grapes
Key3 not found.
map1 is empty.
详解
遍历
#include<map>
#include<iostream>
using namespace std;
int main()
{
map<char,int>;
m['d']=10;
m['e']=20;
m['a']=30;
m['b']=40;
m['c']=50;
m['r']=60;
map<char,int>::iterator it;
for(it = m.begin(); it! =m.end(); it++)
cout<<it->first<<" "<<it->second<<endl;
}
运行结果
查找
map<int,string>::iterator t;
t = m.find(1);
if(t != m.end())
cout << "查找成功!" << endl;
else
cout << "查找失败!" << endl;
插入
//用insert函数插入pair
m.insert(pair<int, string>(111, "kk"));
// 用insert函数插入value_type数据
m.insert(map<int, string>::value_type(222, "pp"));
// 用数组方式插入
m[123] = "dd";
m[456] = "ff";
删除
map<int,string>::iterator t;
//迭代器刪除
it = maps.find("123");
maps.erase(it);
//关键字删除
int n = maps.erase("123"); //如果刪除了返回1,否则返回0
//用迭代器范围刪除 : 把整个map清空
maps.erase(maps.begin(), maps.end());
//等同于mapStudent.clear()
改为递减
//在创造map时,增加参数 std::greater<int>,就变成递减
map<int, int, greater<int> > m;