map容器封装了红黑树,用于查找。
头文件
#include<map>
map容器初始化
#include <iostream>
#include<string>
#include<map>
using namespace std;
int main() {
// 1. 创建一个空的map容器
map<int,string> m1;
// 2. 使用统一初始化列表
map<int,string> m2({{1, "aa"}, {2, "bb"}, {3, "cc"},{4, "dd"},{5, "ee"}});
for(auto& val:m2) {
cout<<"key = "<<val.first<<" value = "<<val.second<<endl;
}
// 3. 拷贝构造函数初始化
map<int,string> m3 = m2;
for(auto& val:m3) {
cout<<"key = "<<val.first<<" value = "<<val.second<<endl;
}
// 4. 用迭代器初始化
auto begin = m3.begin(); begin++;
auto end = m3.end(); end--;
map<int,string> m4(begin, end);
return 0;
}
map容器特性操作
- size 大小
- empty 是否为空
- clear 清空容器
#include <iostream>
#include<string>
#include<map>
using namespace std;
int main() {
map<int,string> m1({{1, "aa"}, {2, "bb"}, {3, "cc"},{4, "dd"},{5, "ee"}});
cout << "m1.size = "<<m1.size() <<endl;
cout << "m1.empty = "<<m1.empty() <<endl;
m1.clear();
cout << "m1.size = "<<m1.size() <<endl;
return 0;
}
map查找元素
在容器中寻找值为k的元素,返回该元素的迭代器。否则,返回map.end()。
iterator find (const key_type& k);
const_iterator find (const key_type& k) const;
#include <iostream>
#include<string>
#include<map>
using namespace std;
int main() {
map<int,string> m1({{1, "aa"}, {2, "bb"}, {3, "cc"},{4, "dd"},{5, "ee"}});
m1.erase(1); // 从m1容器中删除指定key的元素,返回已删除元素的个数
// map<int,string>::iterator it = m1.find(99);
map<int,string>::iterator it = m1.find(2);
if (it != m1.end())
{
cout <<"value = "<<it->second<<endl;
m1.erase(it); // 删除该元素, 返回下一个有效的迭代器
} else {
cout <<"no element was founded "<< endl;
}
return 0;
}
map容器插入
#include <iostream>
#include<string>
#include<map>
using namespace std;
int main() {
map<int,string> m1;
// 1. 用初始化列表在容器中插入多个元素
m1.insert({{1, "aa"}, {2, "bb"}});
m1.insert({make_pair<int,string>(3, "ccc"), pair<int,string>(4, "ddd")});
// 2. 插入一个元素,返回一个pair,first是已插入元素的迭代器,second是插入结果bool类型
auto ret = m1.insert({1, "eeeeeeee"});
if (ret.second == true)
{
cout <<"插入成功ret.first = "<<ret.first->first<<" ret.second = "<<ret.first->second<<endl;
} else {
cout <<"插入失败"<<endl;
}
// 3. 用迭代器插入一个区间的元素
map<int,string> m2({{11, "111"}, {12, "121212"}, {13, "131313"},{14, "141414"},{15, "151515"}});
m1.insert(m2.begin()++,m2.end()--);
// 4. 使用emplace 效率更高
auto ret1 = m1.emplace(pair<int,string>(20, "eeeeeeee"));
if (ret1.second == true)
{
cout <<"插入成功ret1.first = "<<ret1.first->first<<" ret1.second = "<<ret1.first->second<<endl;
} else {
cout <<"插入失败"<<endl;
}
for(auto& val:m1) {
cout<<"key = "<<val.first<<" value = "<<val.second<<endl;
}
return 0;
}
网友评论