STL值map
1.map函数的概念与构造


#include<iostream> using namespace std; #include<map> void printmap(map<int, int>p) { for (map<int, int>::iterator it = p.begin(); it != p.end(); it++) { cout << "键值为:" << (*it).first << "实值:" << it->second << endl; } } int main(void) { //map函数的插入,无论如何插入,map总会按照键值得顺序排列 map<int, int>p; p.insert(pair<int, int>(3, 30)); p.insert(pair<int, int>(2, 20)); p.insert(pair<int, int>(6, 60)); p.insert(pair<int, int>(1, 10)); printmap(p); //map拷贝函数 map<int, int>p2(p); printmap(p2); //map赋值 map<int, int>p3; p3 = p2; printmap(p3); return 0; }
2.map的大小与交换
3.map的插入与删除

#include<iostream> using namespace std; #include<map> void printmap(map<int, int>mp) { for (map<int, int>::iterator it = mp.begin(); it != mp.end(); it++) { cout << it->second << " "; } cout << endl; } int main(void) { map<int, int> mp; //map的插入 //第一种 mp.insert(pair<int, int>(1, 10)); //第二种 mp.insert(make_pair(2, 20)); //第三种 mp.insert(map<int, int>::value_type(3, 30)); //第四种 //[]不建议使用,但可以利用key访问到value mp[4] = 40; cout << mp[4] << endl; printmap(mp); //删除 mp.erase(mp.begin()); printmap(mp); //按照key来删除 mp.erase(4); printmap(mp); //清空 //mp.erase(mp.begin(), mp.end()); mp.clear(); printmap(mp); }
4.map的统计与查找

#include<iostream> using namespace std; #include<map> //map的统计与查找 void printmap(map<int, int>mp) { for (map<int, int>::iterator it = mp.begin(); it != mp.end(); it++) { cout << it->second << " "; } cout << endl; } int main(void) { map<int, int> mp; //查找 mp.insert(make_pair(1, 10)); mp.insert(make_pair(2, 20)); mp.insert(make_pair(3, 30)); mp.insert(make_pair(4, 40)); map<int, int>::iterator pos = mp.find(3);//find查找返回的是一个迭代器,所以用迭代器接受 //如果没有查到那么返回end() if (pos != mp.end()) { cout << "找到了钙元素" << pos->second << endl; } else { cout << "未找到该元素" << endl; } //统计 //map不允许重复插入key元素,count统计而言,要么是0要么是1 //multimap的统计可能大于1 int num = mp.count(3); cout << num << endl; return 0; }
计算机小白记录学习过程,喜欢就点个推荐和关注吧O(∩_∩)O哈哈~

浙公网安备 33010602011771号