|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
The trees that are slow to grow bear the best fruit.
Map
map中所有元素都是pair
pair中第一个元素都为key(键值),起到索引作用,第二元素为value(实值)
所有元素都会根据元素的键值自动排序
map/multimap属于关联式容器,底层结构是用二叉树实现。
优点:
可以根据key值快速找到value值
map和multimap区别:
map不允许容器中有重复key值元素
multimap允许容器中有重复key重复元素
- #include<iostream>
- #include<map>
- using namespace std;
- class Mapcompare
- {
- public:
- bool operator()(int v1,int v2)
- {
- return v1 > v2;
- }
- };
- 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 test1()
- {
- map<int,int>m1;
-
- m1.insert(pair<int,int>(1,100));
- m1.insert(pair<int,int>(2,200));
- m1.insert(pair<int,int>(3,300));
- m1.insert(pair<int,int>(4,400));
-
- printmap(m1);
-
- //拷贝构造
- map<int,int>m2(m1);
- printmap(m2);
-
- //赋值
- map<int,int>m3;
- m3 = m2;
- printmap(m3);
-
- }
- void test2()
- {
- map<int,int>m1;
-
- m1.insert(pair<int,int>(1,200));
- m1.insert(pair<int,int>(2,300));
- m1.insert(pair<int,int>(3,400));
-
- if (m1.empty())
- {
- cout << "m1为空!!!!!!" << endl;
- }
- else
- {
- cout << "m1不为空!!!!!!!" << endl;
- cout << "m1的大小是: " << m1.size() << endl;
- }
-
- map<int,int>m2;
-
- m2.insert(pair<int,int>(1,600));
- m2.insert(pair<int,int>(2,700));
- m2.insert(pair<int,int>(3,800));
-
- cout << "交换前!!!!!!!!!" << endl;
- printmap(m1);
- printmap(m2);
-
- cout << "交换后!!!!!!!!!!" << endl;
- m1.swap(m2);
- printmap(m1);
- printmap(m2);
- }
- void test3()
- {
- map<int,int> m1;
-
- //插入
- m1.insert(pair<int,int>(1,10));
-
- m1.insert(make_pair(2,20));
-
- m1.insert(map<int,int>::value_type(3,30));
-
- m1[4] = 40;
-
- cout << m1[5] << endl;//系统会自动将value赋值为0
-
- printmap(m1);
-
- //删除
- m1.erase(m1.begin());
- printmap(m1);
-
- m1.erase(3);//可以按照key值进行删除
- printmap(m1);
-
- //清空
- m1.erase(m1.begin(),m1.end());
- m1.clear();
- printmap(m1);
- }
- void test4()
- {
- map<int,int>m1;
-
- m1.insert(pair<int,int>(1,200));
- m1.insert(pair<int,int>(2,300));
- m1.insert(pair<int,int>(3,400));
-
- map<int,int>::iterator a = m1.find(2);
-
- if ( a != m1.end())
- {
- cout << "查到元素 key = " << (*a).first << " value : " << a->second << endl;
- }
- else
- {
- cout << "未找到元素!!!!!!!!!!" << endl;
- }
-
- //统计
- //map不允许插入重复key元素,count统计结果不是 0 就是1
- //multimap的count统计结果就可能大于1了
- int num = m1.count(2);
- cout << "num = " << num << endl;
- }
- void test5()
- {
- map<int,int,Mapcompare>m1;
-
- m1.insert(pair<int,int>(1,200));
- m1.insert(pair<int,int>(2,300));
- m1.insert(pair<int,int>(3,400));
-
- for (map<int,int,Mapcompare>::iterator it = m1.begin(); it != m1.end(); it++)
- {
- cout << "key = " << (*it).first << " value = " << it->second << endl;
- }
- cout << endl;
- }
- int main()
- {
- test1();//map构造和赋值
-
- test2();//map大小和交换
-
- test3();//map插入和删除
-
- test4();//map查找和统计
-
- test5();//map排序
-
- return 0;
- }
复制代码

|
|