- map/ multimap容器功能和set/mutiset一样,一个可以相同元素,一个不可以
- map所有都是pair,像python的键值对,按照键值自动排序
- 构造赋值,大小,交换,插入,删除与前面一样,唯一不同的就是pair
- 排序的话,要写仿函数改变排序规则
#include<iostream>
using namespace std;
#include<map>
void printmap(map<int, int>& m)
{
for (map<int, int>::iterator it = m.begin(); it != m.end(); it++)
{
cout << "key = " << it->first << " value = " << it->second << endl;
}
cout << endl;
}
void test01()
{
map<int, int> m;
m.insert(pair<int, int>(1, 10));
m.insert(pair<int, int>(2, 1000));
m.insert(pair<int, int>(3, 100));
m.insert(pair<int, int>(4, 100000));
printmap(m);
map<int, int> m2(m);
printmap(m2);
map<int, int>m3;
m3 = m;
printmap(m3);
}
void test02()
{
map<int, int> m;
m.insert(pair<int, int>(1, 10));
m.insert(pair<int, int>(2, 1000));
m.insert(pair<int, int>(3, 100));
m.insert(pair<int, int>(4, 100000));
printmap(m);
if (m.empty())
{
cout << "m为空" << endl;
}
else
{
cout << "m不为空" << endl;
cout << "m的大小为" << m.size() << endl;
}
map<int, int> m2;
m2.insert(pair<int, int>(5, 90));
m2.insert(pair<int, int>(6, 8000));
m2.insert(pair<int, int>(7, 700));
m2.insert(pair<int, int>(4, 60000));
printmap(m2);
m2.swap(m);
printmap(m);
printmap(m2);
}
void test03()
{
map<int, int> m;
m.insert(pair<int, int>(1, 10));
m.insert(pair<int, int>(2, 1000));
m.insert(pair<int, int>(3, 100));
m.insert(pair<int, int>(4, 100000));
printmap(m);
m.insert(pair<int, int>(10, 50));
m.insert(make_pair(11, 99));
printmap(m);
m.erase(10);
m.erase(m.begin());
printmap(m);
m.erase(m.begin(), m.end());
m.clear();
printmap(m);
}
void test04()
{
map<int, int> m;
m.insert(pair<int, int>(1, 10));
m.insert(pair<int, int>(2, 1000));
m.insert(pair<int, int>(3, 100));
m.insert(pair<int, int>(4, 100000));
printmap(m);
map<int, int>::iterator pos = m.find(4);
if (pos != m.end())
{
cout << "找到了元素 key = " << (*pos).first << " value = " << (*pos).second << endl;
}
else
{
cout << "未找到元素" << endl;
}
int num = m.count(3);
cout << "num = " << num << endl;
}
class Mycompare
{
public:
bool operator()(int v1, int v2) const
{
return v1 > v2;
}
};
void test05()
{
map<int, int,Mycompare> m;
m.insert(pair<int, int>(1, 10));
m.insert(pair<int, int>(2, 1000));
m.insert(pair<int, int>(3, 100));
m.insert(pair<int, int>(4, 100000));
for (map<int, int, Mycompare>::iterator it = m.begin(); it != m.end(); it++)
{
cout << "key = " << it->first << " value = " << it->second << endl;
}
}
int main()
{
test01();
test02();
test03();
test04();
test05();
return 0;
}