-
Notifications
You must be signed in to change notification settings - Fork 8.6k
/
map_insert_look.cpp
80 lines (75 loc) · 2.42 KB
/
map_insert_look.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/* 字典插入与查找.cpp */
#include <cstring>
#include <iostream>
#include <map>
using namespace std;
int main(int argc, char const *argv[]) {
map<const char *, const char *> mp;
map<const char *, const char *>::iterator iter;
const char key[3][20] = {"img", "system", "ip"};
const char value[3][20] = {"d:/a.img", "win7", "193.68.6.3"};
// make_pair插入
for (int i = 0; i < 2; i++) {
mp.insert(make_pair(key[i], value[i]));
}
// pair<const char*,const char*>插入
mp.insert(pair<const char *, const char *>(key[2], value[2]));
//数组插入方式
mp["addr"] = "中国";
//迭代器取出元素
//循环取出元素
for (iter = mp.begin(); iter != mp.end(); iter++) {
cout << iter->first << "\t" << iter->second << endl;
}
char key1[20];
cout << "请输入按key查找:";
cin.getline(key1, 20);
//查找元素
for (iter = mp.begin(); iter != mp.end(); iter++) {
if (strcmp(iter->first, key1) == 0) {
cout << iter->first << "查找出来了!"
<< "对应的值为:" << iter->second << endl;
}
}
//第一种删除方式
// find只能用于查找数组建立的形式!并且不支持输入用cin等
iter = mp.find("addr");
if (iter != mp.end()) {
cout << iter->first << "按照key查找出来了!"
<< "对应的value为:" << iter->second << endl;
cout << "开始删除元素!" << endl;
mp.erase(iter);
// break;
}
//第二种方式删除
//按照key删除元素
char drop_key[20];
//按照value删除元素
char drop_value[20];
cout << "请输入按key删除:";
cin.getline(drop_key, 20);
cout << "请输入按value删除:";
cin.getline(drop_value, 20);
for (iter = mp.begin(); iter != mp.end(); iter++) {
if (strcmp(iter->first, drop_key) == 0) {
cout << iter->first << "按照key查找出来了!"
<< "对应的value为:" << iter->second << endl;
cout << "开始删除元素!" << endl;
mp.erase(iter);
break;
}
if (strcmp(iter->second, drop_value) == 0) {
cout << iter->second << "value查找出来了!"
<< "对应的key为:" << iter->first << endl;
cout << "开始删除元素!" << endl;
mp.erase(iter);
break;
}
}
cout << "------删除元素以后--------\n";
//循环取出元素
for (iter = mp.begin(); iter != mp.end(); iter++) {
cout << iter->first << "\t" << iter->second << endl;
}
return 0;
}