#include <iostream> #include <thread> #include<map> #include <algorithm> #include <vector> #ifdef lniux #include <unistd.h> //usleep(1000000); #else #include <Windows.h> #include <WinBase.h> #endif using namespace std; void test1_pair() { // pair测试 typedef pair<string, string> Author; Author proust("March", "Proust"); cout << "pair 测试 first:" << proust.first << " second: " << proust.second << endl; } void test1_insert() { //第一种:用insert函数插入pair数据: map<int, string> my_map; my_map.insert(pair<int, string>(1, "first")); my_map.insert(pair<int, string>(2, "second")); my_map.insert(map<int, string>::value_type(3, "2")); my_map.insert(map<int, string>::value_type(4, "3")); my_map[5] = "5"; my_map[6] = "6"; //std::cout << my_map[1] << endl; //std::cout << my_map[2] << endl; map<int, string>::iterator it; for (it = my_map.begin(); it != my_map.end(); it++) cout << "map测试 first: " << it->first << " second: " << it->second << endl; } void test2_find() { //查找 判断关键字是否出现 map< string, int> myfing_map; myfing_map.insert(pair<string, int>("dongdong", 21)); myfing_map.insert(pair<string, int>("xixi", 22)); myfing_map.insert(pair<string, int>("lala", 23)); map<string, int>::iterator it1; it1 = myfing_map.find("dongdong"); if (it1 != myfing_map.end()) cout << "Find, the value is " << it1->second << endl; else cout << "Do not Find" << endl; } void test4_erase() { map<int, string> my_map; my_map.insert(pair<int, string>(1, "one")); my_map.insert(pair<int, string>(2, "two")); my_map.insert(pair<int, string>(3, "three")); //如果你要演示输出效果,请选择以下的一种,你看到的效果会比较好 //如果要删除1,用迭代器删除 map<int, string>::iterator it; it = my_map.find(1); my_map.erase(it); //如果要删除1,用关键字删除 int n = my_map.erase(1); //如果删除了会返回1,否则返回0 //用迭代器,成片的删除 //一下代码把整个map清空 my_map.erase(my_map.begin(), my_map.end()); //成片删除要注意的是,也是STL的特性,删除区间是一个前闭后开的集合 //自个加上遍历代码,打印输出吧 } bool cmp(pair<string, int> a, pair<string, int> b) { return a.second < b.second; } void test3_sort() { // 排序 map<string, int> ma; ma["Alice"] = 86; ma["Bob"] = 78; ma["Zip"] = 92; ma["Stdevn"] = 88; //vector< pair<string, int> > vec(ma.begin(), ma.end()); vector< pair<string, int> > vec; for (map<string, int>::iterator it = ma.begin(); it != ma.end(); it++) vec.push_back(pair<string, int>(it->first, it->second)); sort(vec.begin(), vec.end(), cmp); for (vector< pair<string, int> >::iterator it = vec.begin(); it != vec.end(); ++it) { cout << it->first << " " << it->second << endl; } } int main(int argc, char** argv) { test1_pair(); test1_insert(); test2_find(); test3_sort(); test4_erase(); }
标签:map,include,ma,insert,pair,数据结构,my From: https://www.cnblogs.com/gooutlook/p/16934830.html