总结

  1. 底层实现是 rb_tree,因此是有序的,即会按照key的值从小到大排序(默认less函数)
  2. insert的元素是由键值对组成的pair
  3. 主要操作API有:insert、empty、size、erase、find;insert返回的pair结构,pair 当插入成功 bool 为true,iterator为对应的迭代器
  4. map所有的节点元素都是组成pair结构
  5. 因为要保持唯一,因此调用的rb_tree的 insert_unique
  6. map的迭代器是双向迭代器
  7. map有自带的lower_bound和upper_bound
  8. 插入值的方法是insert,没有push,push方法对应的容器都是有特性的,比如stack、queue、priority_queue,而push_back/push_front则是对应vector/deque


  1. struct myCmp2
  2. {
  3. bool operator() (pair<int, int>& m, pair<int, int>& n)
  4. {
  5. if (m.first == n.first) return m.second > n.second;
  6. return m.first > n.first;
  7. }
  8. };
  9. int main()
  10. {
  11. map<pair<int, int>, int> myMap2; // map可以直接把pair当作key,而且他可以接收的是自定义的排序算法,而不是hash算法
  12. // map<pair<int, int>, int, myCmp2> myMap3;
  13. myMap2[{1, 1}] = 1;
  14. myMap2[{2, 2}] = 2;
  15. myMap2[{2, 1}] = 3;
  16. myMap2[{1, 2}] = 4;
  17. for (auto& kv: myMap2)
  18. {
  19. std::cout << kv.first.first << " " << kv.first.second << " " << kv.second << std::endl;
  20. }
  21. }

map结构

  1. #ifndef __SGI_STL_INTERNAL_MAP_H
  2. #define __SGI_STL_INTERNAL_MAP_H
  3. #include <concept_checks.h>
  4. __STL_BEGIN_NAMESPACE
  5. #if defined(__sgi) && !defined(__GNUC__) && (_MIPS_SIM != _MIPS_SIM_ABI32)
  6. #pragma set woff 1174
  7. #pragma set woff 1375
  8. #endif
  9. /*
  10. map的所有节点元素都是pair,pair有两个成员变量first,second
  11. 第一个first是键值key,第二个second是实值value
  12. 有关pair的定义见前文<stl_pair.h>剖析
  13. */
  14. //map内部元素根据键值key默认使用递增排序less//用户可自行制定比较类型//内部维护的数据结构是红黑树, 具有非常优秀的最坏情况的时间复杂度 //注意:map键值和实值是分开的,map的键值key是唯一的,实值value可以重复//不能通过迭代器修改map的键值key,其迭代器类型是定义为RB-Tree的const_iterator//但是可以通过迭代器修改map的实值value
  15. // Forward declarations of operators == and <, needed for friend declarations.
  16. template <class _Key, class _Tp,
  17. class _Compare __STL_DEPENDENT_DEFAULT_TMPL(less<_Key>),
  18. class _Alloc = __STL_DEFAULT_ALLOCATOR(_Tp) >
  19. class map;
  20. template <class _Key, class _Tp, class _Compare, class _Alloc>
  21. inline bool operator==(const map<_Key,_Tp,_Compare,_Alloc>& __x,
  22. const map<_Key,_Tp,_Compare,_Alloc>& __y);
  23. template <class _Key, class _Tp, class _Compare, class _Alloc>
  24. inline bool operator<(const map<_Key,_Tp,_Compare,_Alloc>& __x,
  25. const map<_Key,_Tp,_Compare,_Alloc>& __y);
  26. //map定义
  27. template <class _Key, class _Tp, class _Compare, class _Alloc>
  28. class map {
  29. public:
  30. // requirements:
  31. __STL_CLASS_REQUIRES(_Tp, _Assignable);
  32. __STL_CLASS_BINARY_FUNCTION_CHECK(_Compare, bool, _Key, _Key);
  33. // typedefs:
  34. typedef _Key key_type;//键值key类型
  35. typedef _Tp data_type;//数据(实值)value类型
  36. typedef _Tp mapped_type;
  37. typedef pair<const _Key, _Tp> value_type;//元素型别,包含(键值/实值),const保证键值key不被修改
  38. typedef _Compare key_compare;//键值key比较函数
  39. //嵌套类,提供键值key比较函数接口
  40. //继承自<stl_function.h>中的binary_function
  41. /*
  42. template <class _Arg1, class _Arg2, class _Result>
  43. struct binary_function {
  44. typedef _Arg1 first_argument_type;
  45. typedef _Arg2 second_argument_type;
  46. typedef _Result result_type;
  47. };
  48. */
  49. class value_compare
  50. : public binary_function<value_type, value_type, bool> {
  51. friend class map<_Key,_Tp,_Compare,_Alloc>;
  52. protected :
  53. _Compare comp;
  54. value_compare(_Compare __c) : comp(__c) {}
  55. public:
  56. bool operator()(const value_type& __x, const value_type& __y) const {
  57. return comp(__x.first, __y.first);//以键值调用比较函数
  58. }
  59. };
  60. private:
  61. //底层机制是RB-Tree
  62. //以map类型(一个pair)的第一个类型作为TB-tree的键值类型.
  63. //所以在RB-tree中,键值key不能修改
  64. typedef _Rb_tree<key_type, value_type,
  65. _Select1st<value_type>, key_compare, _Alloc> _Rep_type;
  66. _Rep_type _M_t; // red-black tree representing map
  67. public:
  68. typedef typename _Rep_type::pointer pointer;
  69. typedef typename _Rep_type::const_pointer const_pointer;
  70. typedef typename _Rep_type::reference reference;
  71. typedef typename _Rep_type::const_reference const_reference;
  72. //map的迭代器不直接定义为const_iterator,而是分别定义iterator,const_iterator
  73. //是因为map的键值key不能被修改,所以必须定义为const_iterator
  74. //而map的实值value可以被修改,则定义为iterator
  75. typedef typename _Rep_type::iterator iterator;
  76. typedef typename _Rep_type::const_iterator const_iterator;
  77. typedef typename _Rep_type::reverse_iterator reverse_iterator;
  78. typedef typename _Rep_type::const_reverse_iterator const_reverse_iterator;
  79. typedef typename _Rep_type::size_type size_type;
  80. typedef typename _Rep_type::difference_type difference_type;
  81. typedef typename _Rep_type::allocator_type allocator_type;
  82. // allocation/deallocation
  83. // map只能使用RB-tree的insert-unique(),不能使用insert-equal()
  84. //因为必须保证键值唯一
  85. /*
  86. 构造函数
  87. map();
  88. explicit map (const key_compare& comp = key_compare(),
  89. const allocator_type& alloc = allocator_type());
  90. template <class InputIterator>
  91. map (InputIterator first, InputIterator last,
  92. const key_compare& comp = key_compare(),
  93. const allocator_type& alloc = allocator_type());
  94. map (const map& x);
  95. */
  96. /*
  97. example:
  98. #include <iostream>
  99. #include <map>
  100. bool fncomp (char lhs, char rhs) {return lhs<rhs;}
  101. struct classcomp {
  102. bool operator() (const char& lhs, const char& rhs) const
  103. {return lhs<rhs;}
  104. };
  105. int main ()
  106. {
  107. std::map<char,int> first;
  108. first['a']=10;
  109. first['b']=30;
  110. first['c']=50;
  111. first['d']=70;
  112. std::map<char,int> second (first.begin(),first.end());
  113. std::map<char,int> third (second);
  114. std::map<char,int,classcomp> fourth; // class as Compare
  115. bool(*fn_pt)(char,char) = fncomp;
  116. std::map<char,int,bool(*)(char,char)> fifth (fn_pt); // function pointer as Compare
  117. return 0;
  118. }
  119. */
  120. map() : _M_t(_Compare(), allocator_type()) {}
  121. explicit map(const _Compare& __comp,
  122. const allocator_type& __a = allocator_type())
  123. : _M_t(__comp, __a) {}
  124. #ifdef __STL_MEMBER_TEMPLATES
  125. template <class _InputIterator>
  126. map(_InputIterator __first, _InputIterator __last)
  127. : _M_t(_Compare(), allocator_type())
  128. { _M_t.insert_unique(__first, __last); }
  129. template <class _InputIterator>
  130. map(_InputIterator __first, _InputIterator __last, const _Compare& __comp,
  131. const allocator_type& __a = allocator_type())
  132. : _M_t(__comp, __a) { _M_t.insert_unique(__first, __last); }
  133. #else
  134. map(const value_type* __first, const value_type* __last)
  135. : _M_t(_Compare(), allocator_type())
  136. { _M_t.insert_unique(__first, __last); }
  137. map(const value_type* __first,
  138. const value_type* __last, const _Compare& __comp,
  139. const allocator_type& __a = allocator_type())
  140. : _M_t(__comp, __a) { _M_t.insert_unique(__first, __last); }
  141. map(const_iterator __first, const_iterator __last)
  142. : _M_t(_Compare(), allocator_type())
  143. { _M_t.insert_unique(__first, __last); }
  144. map(const_iterator __first, const_iterator __last, const _Compare& __comp,
  145. const allocator_type& __a = allocator_type())
  146. : _M_t(__comp, __a) { _M_t.insert_unique(__first, __last); }
  147. #endif /* __STL_MEMBER_TEMPLATES */
  148. //拷贝构造函数
  149. map(const map<_Key,_Tp,_Compare,_Alloc>& __x) : _M_t(__x._M_t) {}
  150. //这里提供了operator=,即可以通过=初始化对象
  151. map<_Key,_Tp,_Compare,_Alloc>&
  152. operator=(const map<_Key, _Tp, _Compare, _Alloc>& __x)
  153. {
  154. _M_t = __x._M_t;
  155. return *this;
  156. }
  157. // accessors:
  158. //以下调用RB-Tree的操作
  159. //返回键值的比较函数,这里是调用RB-Tree的key_comp()
  160. key_compare key_comp() const { return _M_t.key_comp(); }
  161. //返回实值的比较函数
  162. //这里调用的是map嵌套类中定义的比较函数
  163. /*
  164. class value_compare
  165. : public binary_function<value_type, value_type, bool> {
  166. friend class map<_Key,_Tp,_Compare,_Alloc>;
  167. protected :
  168. _Compare comp;
  169. value_compare(_Compare __c) : comp(__c) {}
  170. public:
  171. bool operator()(const value_type& __x, const value_type& __y) const {
  172. return comp(__x.first, __y.first);//以键值调用比较函数
  173. }
  174. */
  175. //实际上最终还是调用键值key的比较函数,即他们是调用同一个比较函数
  176. value_compare value_comp() const { return value_compare(_M_t.key_comp()); }
  177. //获得分配器的类型
  178. allocator_type get_allocator() const { return _M_t.get_allocator(); }
  179. iterator begin() { return _M_t.begin(); }
  180. const_iterator begin() const { return _M_t.begin(); }
  181. iterator end() { return _M_t.end(); }
  182. const_iterator end() const { return _M_t.end(); }
  183. reverse_iterator rbegin() { return _M_t.rbegin(); }
  184. const_reverse_iterator rbegin() const { return _M_t.rbegin(); }
  185. reverse_iterator rend() { return _M_t.rend(); }
  186. const_reverse_iterator rend() const { return _M_t.rend(); }
  187. bool empty() const { return _M_t.empty(); }
  188. size_type size() const { return _M_t.size(); }
  189. size_type max_size() const { return _M_t.max_size(); }
  190. //重载operator[],返回是实值value(即pair.second)的引用
  191. //注意:若你原先没有定义map对象,即你访问的键值key不存在,则会自动新建一个map对象
  192. //键值key为你访问的键值key,实值value为空,看下面的例子就明白了
  193. _Tp& operator[](const key_type& __k) {
  194. iterator __i = lower_bound(__k);
  195. // __i->first is greater than or equivalent to __k.
  196. if (__i == end() || key_comp()(__k, (*__i).first))
  197. __i = insert(__i, value_type(__k, _Tp()));
  198. return (*__i).second;
  199. //其实简单的方式是直接返回
  200. //return (*((insert(value_type(k, T()))).first)).second;
  201. }
  202. /*
  203. example:
  204. #include <iostream>
  205. #include <map>
  206. #include <string>
  207. int main ()
  208. {
  209. std::map<char,std::string> mymap;
  210. mymap['a']="an element";
  211. mymap['b']="another element";
  212. mymap['c']=mymap['b'];
  213. std::cout << "mymap['a'] is " << mymap['a'] << '\n';
  214. std::cout << "mymap['b'] is " << mymap['b'] << '\n';
  215. std::cout << "mymap['c'] is " << mymap['c'] << '\n';
  216. std::cout << "mymap['d'] is " << mymap['d'] << '\n';
  217. std::cout << "mymap now contains " << mymap.size() << " elements.\n";
  218. return 0;
  219. }
  220. Ouput:
  221. mymap['a'] is an element
  222. mymap['b'] is another element
  223. mymap['c'] is another element
  224. mymap['d'] is
  225. mymap now contains 4 elements.
  226. */
  227. //交换map对象的内容
  228. void swap(map<_Key,_Tp,_Compare,_Alloc>& __x) { _M_t.swap(__x._M_t); }
  229. // insert/erase
  230. /*
  231. 插入元素
  232. single element (1):
  233. pair<iterator,bool> insert (const value_type& val);
  234. with hint (2):
  235. iterator insert (iterator position, const value_type& val);
  236. range (3):
  237. template <class InputIterator>
  238. void insert (InputIterator first, InputIterator last);
  239. */
  240. //插入元素节点,调用RB-Tree的insert_unique(__x);
  241. //不能插入相同键值的元素
  242. pair<iterator,bool> insert(const value_type& __x)
  243. { return _M_t.insert_unique(__x); }
  244. //在指定位置插入元素,但是会先遍历该集合,判断是否存在相同元素
  245. //若不存在才在指定位置插入该元素
  246. iterator insert(iterator position, const value_type& __x)
  247. { return _M_t.insert_unique(position, __x); }
  248. #ifdef __STL_MEMBER_TEMPLATES
  249. template <class _InputIterator>
  250. void insert(_InputIterator __first, _InputIterator __last) {
  251. _M_t.insert_unique(__first, __last);
  252. }
  253. #else
  254. void insert(const value_type* __first, const value_type* __last) {
  255. _M_t.insert_unique(__first, __last);
  256. }
  257. void insert(const_iterator __first, const_iterator __last) {
  258. _M_t.insert_unique(__first, __last);
  259. }
  260. #endif /* __STL_MEMBER_TEMPLATES */
  261. /*
  262. 擦除元素
  263. void erase (iterator position);
  264. size_type erase (const key_type& k);
  265. void erase (iterator first, iterator last);
  266. */
  267. //在指定位置擦除元素
  268. void erase(iterator __position) { _M_t.erase(__position); }
  269. //擦除指定键值的节点
  270. size_type erase(const key_type& __x) { return _M_t.erase(__x); }
  271. //擦除指定区间的节点
  272. void erase(iterator __first, iterator __last)
  273. { _M_t.erase(__first, __last); }
  274. //清空map
  275. void clear() { _M_t.clear(); }
  276. // map operations:
  277. //查找指定键值的节点
  278. iterator find(const key_type& __x) { return _M_t.find(__x); }
  279. const_iterator find(const key_type& __x) const { return _M_t.find(__x); }
  280. //计算指定键值元素的个数
  281. size_type count(const key_type& __x) const {
  282. return _M_t.find(__x) == _M_t.end() ? 0 : 1;
  283. }
  284. /*
  285. Example:
  286. #include <iostream>
  287. #include <map>
  288. int main ()
  289. {
  290. std::map<char,int> mymap;
  291. std::map<char,int>::iterator itlow,itup;
  292. mymap['a']=20;
  293. mymap['b']=40;
  294. mymap['c']=60;
  295. mymap['d']=80;
  296. mymap['e']=100;
  297. itlow=mymap.lower_bound ('b'); // itlow points to b
  298. itup=mymap.upper_bound ('d'); // itup points to e (not d!)
  299. mymap.erase(itlow,itup); // erases [itlow,itup)
  300. // print content:
  301. for (std::map<char,int>::iterator it=mymap.begin(); it!=mymap.end(); ++it)
  302. std::cout << it->first << " => " << it->second << '\n';
  303. return 0;
  304. }
  305. Output:
  306. a => 20
  307. e => 100
  308. */
  309. //Returns an iterator pointing to the first element in the container
  310. //whose key is not considered to go before k (i.e., either it is equivalent or goes after).
  311. //this->first is greater than or equivalent to __x.
  312. iterator lower_bound(const key_type& __x) {return _M_t.lower_bound(__x); }
  313. const_iterator lower_bound(const key_type& __x) const {
  314. return _M_t.lower_bound(__x);
  315. }
  316. //Returns an iterator pointing to the first element that is greater than key.
  317. iterator upper_bound(const key_type& __x) {return _M_t.upper_bound(__x); }
  318. const_iterator upper_bound(const key_type& __x) const {
  319. return _M_t.upper_bound(__x);
  320. }
  321. //Returns the bounds of a range that includes all the elements in the container
  322. //which have a key equivalent to k
  323. //Because the elements in a map container have unique keys,
  324. //the range returned will contain a single element at most.
  325. pair<iterator,iterator> equal_range(const key_type& __x) {
  326. return _M_t.equal_range(__x);
  327. }
  328. pair<const_iterator,const_iterator> equal_range(const key_type& __x) const {
  329. return _M_t.equal_range(__x);
  330. }
  331. /*
  332. Example:
  333. #include <iostream>
  334. #include <map>
  335. int main ()
  336. {
  337. std::map<char,int> mymap;
  338. mymap['a']=10;
  339. mymap['b']=20;
  340. mymap['c']=30;
  341. std::pair<std::map<char,int>::iterator,std::map<char,int>::iterator> ret;
  342. ret = mymap.equal_range('b');
  343. std::cout << "lower bound points to: ";
  344. std::cout << ret.first->first << " => " << ret.first->second << '\n';
  345. std::cout << "upper bound points to: ";
  346. std::cout << ret.second->first << " => " << ret.second->second << '\n';
  347. return 0;
  348. }
  349. Output:
  350. lower bound points to: 'b' => 20
  351. upper bound points to: 'c' => 30
  352. */
  353. //以下是操作符重载
  354. #ifdef __STL_TEMPLATE_FRIENDS
  355. template <class _K1, class _T1, class _C1, class _A1>
  356. friend bool operator== (const map<_K1, _T1, _C1, _A1>&,
  357. const map<_K1, _T1, _C1, _A1>&);
  358. template <class _K1, class _T1, class _C1, class _A1>
  359. friend bool operator< (const map<_K1, _T1, _C1, _A1>&,
  360. const map<_K1, _T1, _C1, _A1>&);
  361. #else /* __STL_TEMPLATE_FRIENDS */
  362. friend bool __STD_QUALIFIER
  363. operator== __STL_NULL_TMPL_ARGS (const map&, const map&);
  364. friend bool __STD_QUALIFIER
  365. operator< __STL_NULL_TMPL_ARGS (const map&, const map&);
  366. #endif /* __STL_TEMPLATE_FRIENDS */};
  367. //比较两个map的内容
  368. template <class _Key, class _Tp, class _Compare, class _Alloc>
  369. inline bool operator==(const map<_Key,_Tp,_Compare,_Alloc>& __x,
  370. const map<_Key,_Tp,_Compare,_Alloc>& __y) {
  371. return __x._M_t == __y._M_t;}
  372. template <class _Key, class _Tp, class _Compare, class _Alloc>
  373. inline bool operator<(const map<_Key,_Tp,_Compare,_Alloc>& __x,
  374. const map<_Key,_Tp,_Compare,_Alloc>& __y) {
  375. return __x._M_t < __y._M_t;}
  376. #ifdef __STL_FUNCTION_TMPL_PARTIAL_ORDER
  377. template <class _Key, class _Tp, class _Compare, class _Alloc>
  378. inline bool operator!=(const map<_Key,_Tp,_Compare,_Alloc>& __x,
  379. const map<_Key,_Tp,_Compare,_Alloc>& __y) {
  380. return !(__x == __y);}
  381. template <class _Key, class _Tp, class _Compare, class _Alloc>
  382. inline bool operator>(const map<_Key,_Tp,_Compare,_Alloc>& __x,
  383. const map<_Key,_Tp,_Compare,_Alloc>& __y) {
  384. return __y < __x;}
  385. template <class _Key, class _Tp, class _Compare, class _Alloc>
  386. inline bool operator<=(const map<_Key,_Tp,_Compare,_Alloc>& __x,
  387. const map<_Key,_Tp,_Compare,_Alloc>& __y) {
  388. return !(__y < __x);}
  389. template <class _Key, class _Tp, class _Compare, class _Alloc>
  390. inline bool operator>=(const map<_Key,_Tp,_Compare,_Alloc>& __x,
  391. const map<_Key,_Tp,_Compare,_Alloc>& __y) {
  392. return !(__x < __y);}
  393. template <class _Key, class _Tp, class _Compare, class _Alloc>
  394. inline void swap(map<_Key,_Tp,_Compare,_Alloc>& __x,
  395. map<_Key,_Tp,_Compare,_Alloc>& __y) {
  396. __x.swap(__y);}
  397. #endif /* __STL_FUNCTION_TMPL_PARTIAL_ORDER */
  398. #if defined(__sgi) && !defined(__GNUC__) && (_MIPS_SIM != _MIPS_SIM_ABI32)
  399. #pragma reset woff 1174
  400. #pragma reset woff 1375
  401. #endif
  402. __STL_END_NAMESPACE
  403. #endif /* __SGI_STL_INTERNAL_MAP_H */
  404. // Local Variables:// mode:C++// End: