#include <iostream>
#include <map>
#include <algorithm>
using namespace std;
void printMap(const map<int, int> &m)
{
for (map<int, int>::const_iterator it = m.begin(); it != m.end(); ++it)
cout << "key = " << it->first << ", value = " << it->second << endl;
}
void test01()
{
//构造
map<int, int> m1{{1, 10}, {2, 20}, {3, 30}};
printMap(m1);
map<int, int> m2(m1);
printMap(m2);
map<int, int> m3 = m1;
printMap(m3);
}
void test02()
{
map<int, int> m1{{1, 10}, {2, 20}, {3, 30}};
if (m1.empty())
{
cout << "m1为空!" << endl;
}
else
{
cout << "m1不为空,大小为" << m1.size() << endl;
for_each(m1.begin(), m1.end(), [&](const pair<int, int> &p) {
cout << "key = " << p.first << ", value = " << p.second << endl;
});
}
//交换
map<int, int> m2{{4, 40}, {5, 50}, {6, 60}};
m1.swap(m2);
cout << "交换后" << endl;
printMap(m1);
}
void test03()
{
map<int, char> m1;
m1.insert(pair<int, char>(0, 'a'));
m1.insert(make_pair(1, 'b'));
m1.insert(map<int, char>::value_type(2, 'c'));
m1[3] = 'd';
for_each(m1.begin(), m1.end(), [&](const pair<int, char> p) {
cout << "key = " << p.first << ", value = " << p.second << endl;
});
//删除
m1.erase(m1.begin());
m1.erase(2);
for_each(m1.begin(), m1.end(), [&](const pair<int, char> p) {
cout << "key = " << p.first << ", value = " << p.second << endl;
});
map<int, char>::iterator pos = m1.find(3);
if (pos == m1.end())
{
cout << "未找到元素" << endl;
}
else
{
int num = m1.count(3);
cout << "找到了元素key = " << pos->first << ", value = " << pos->second \
<< ", 该元素有" << num << "个" << endl;
}
//清空
//m1.erase(m1.begin(), m1.end());
m1.clear();
}
int main(int argc, char const *argv[])
{
/*1. map中所有元素都是pair,pair中第一个元素是key(键值),起到索引作用,第二个元素是value(实值)
2. 所有元素都会根据元素的键值自动排序
3. 优点:可以根据key值快速找到value值
4. map不允许容器中有重复的key值元素,multimap允许容器中有重复key值元素*/
//构造
test01();
//大小和交换
test02();
//插入和删除
test03();
return 0;
}
STL-map/multimap
最新推荐文章于 2024-08-21 18:16:36 发布