C++中map的使用
1. 基本构造函数
标准的STL map是以红黑树为底层机制完成的,每一个节点的内容是一个pair
map<string, int> strMap
map<int, string> intMap
2. map添加数据
map<int, string> maplive
pair<int, string> value(1, "a");
maplive.insert(value);
maplive.insert(pair<int, string>(1,"a"));
maplive[1] = “a”
(map中最简单最常用的插入添加)
3. map的基本操作函数
begin()
返回指向map头部的迭代器
clear()
删除所有元素
count()
返回指定元素出现的次数
empty()
如果map为空则返回true
end()
返回指向map末尾的迭代器
equal_range()
返回特殊条目的迭代器对
erase()
删除一个元素
find()
查找一个元素
get_allocator()
返回map的配置器
insert()
插入元素
key_comp()
返回比较元素key的函数
lower_bound()
返回键值 >= 给定元素的第一个位置
max_size()
返回可以容纳的最大元素个数
rbegin()
返回一个指向map尾部的逆向迭代器
rend()
返回一个指向map头部的逆向迭代器
size()
返回map中元素的个数
swap()
交换两个map
upper_bound()
返回键值 > 给定元素的第一个位置
value_comp()
返回比较元素value的函数
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 #include <bits/stdc++.h> using namespace std ;int main () { map <string , int > strMap; strMap[string ("jjhou" )] = 1 ; strMap[string ("jerry" )] = 2 ; strMap[string ("jason" )] = 3 ; pair<string , int > temp("jimmy" , 4 ); strMap.insert(temp); strMap.insert(pair<string , int >("david" , 5 )); map <string , int >::iterator strmap_iter = strMap.begin(); for (; strmap_iter != strMap.end();strmap_iter++) { cout << strmap_iter->first << " " << strmap_iter->second << endl ; } cout << endl ; int num = strMap[string ("jjhou" )]; cout << "number = " << num << endl << endl ; map <string , int >::iterator iter1; iter1 = strMap.find(string ("jerry" )); if (iter1 != strMap.end()) { cout << "jerry found" << endl << endl ; } iter1->second = 9 ; int number = strMap[string ("jerry" )]; cout << "number = " << number << endl ; map <string , int >::iterator strmap_iter1 = strMap.begin(); for (;strmap_iter1 != strMap.end();strmap_iter1++) { cout << strmap_iter1->first << " " << strmap_iter1->second << endl ; } cout << endl ; strMap.erase(iter1); strMap.erase(string ("jason" )); map <string , int >::iterator strmap_iter2 = strMap.begin(); for (;strmap_iter2 != strMap.end();strmap_iter2++) { cout << strmap_iter2->first << " " << strmap_iter2->second << endl ; } cout << endl ; }