以下是对map容器的讲解: map容器有一个索引值,相当于位置,还有一个就是我们的真值,map容器和set容器一样会自动进行排列,底层也是二叉树。
#include using namespace std; #include void print(map&m) { for (map::iterator it = m.begin(); it != m.end(); it++) { cout << "key值为:" << (*it).first << " " << "初始化的值为: " << it->second << endl; } cout << endl; } //以下是pair的初始化 void initializepair() { //对组创建的两种方式 pairp1("小刘", 20); cout << "姓名:" << p1.first << " " << " 年龄:" << p1.second << endl; pairp2 = make_pair("小王", 26); cout << "姓名:" << p2.first << " " << " 年龄:" << p2.second << endl; } //以下是map容器的初始化,构造的用法 void test1() { //由于map容器是对组,所以创建的时候需要两个数据类型,且插入数组的时候需要用pair来创建且map容器也会自动进行排列 mapm; m.insert(pair(1, 6)); m.insert(pair(3, 8)); m.insert(pair(2, 1)); m.insert(pair(4, 2)); print(m); mapm2(m); print(m2); mapm3; m3 = m2; print(m3); } //以下是交换功能的实现和求大小,判空的实现 void test2() { mapm2; m2.insert(pair(1, 16)); m2.insert(pair(3, 18)); m2.insert(pair(2, 21)); m2.insert(pair(4, 22)); if (m2.empty()) { cout << "为空!" << endl; } else { cout << "不为空!" << endl; } cout << "大小为:" << m2.size() << endl; mapm3; m3.insert(pair(5, 56)); m3.insert(pair(6, 58)); m3.insert(pair(7, 51)); m3.insert(pair(8, 52)); cout << "未交换前:" << endl; print(m3); cout << "交换后:" << endl; m2.swap(m3); print(m3); } //以下是插入和删除函数 void test3() { mapm3; //m3.insert(2,66);//运行时会报错,错误的方法 //以下两种就是创建对组的方式进行插入 m3.insert(pair(1, 10));//相当于用了匿名对象 m3.insert(make_pair(2, 20)); m3.insert(map::value_type(3, 30));//不建议使用 m3[4] = 40;//一般用[]来获取值,不用来进行插入操作。 print(m3); m3.erase(m3.begin());//删除起始位置的元素 print(m3); m3.erase(3);//删除key为3所对应的数值 print(m3); m3.erase(m3.begin(),m3.end());//相当于清空操作 print(m3); m3.clear(); print(m3); } //以下是find函数和统计count函数 void test4() { mapm4; m4.insert(pair(1, 11));//相当于用了匿名对象 m4.insert(make_pair(2, 22)); m4.insert(map::value_type(3, 33)); m4[4] = 55; m4.insert(pair(3, 88)); print(m4); map::iterator it=m4.find(4); if (it != m4.end()) { cout << "找到了且key和值分别为:" << (*it).first << " " << it->second<b // int operator()(int a, int b) // { // return a > b; // } //}; //void test6() //{ // // mapm6; // // m6.insert(pair(1, 16)); // m6.insert(pair(3, 18)); // m6.insert(pair(2, 21)); // m6.insert(pair(4, 22)); // for (map::iterator it = m6.begin(); it != m6.end(); it++) // { // cout << (*it).first << it->second << endl; // } // cout << endl; //} int main() { test1(); test2(); test3(); test4(); system("pause"); return 0; }
希望我的代码能对大家起到一点点的帮助。
上一篇 C++ Primer 5th笔记(chap 19 特殊工具与技术)两种不可移植的特性之“位域”
下一篇 EduCoder-程序设计技术R(第二部分)- 第1关:加法运算
版权所有 (c)2021-2022 MSHXW.COM
ICP备案号:晋ICP备2021003244-6号