std::map

  1. template < class Key, // map::key_type
  2. class T, // map::mapped_type
  3. class Compare = less<Key>, // map::key_compare
  4. class Alloc = allocator<pair<const Key,T> > // map::allocator_type
  5. > class map;

Map

Maps are associative containers that store elements formed by a combination of a key value and a mapped value, following a specific order.

In a map, the key values are generally used to sort and uniquely identify the elements, while the mapped values store the content associated to this key. The types of key and mapped value may differ, and are grouped together in member type value_type, which is a pair type combining both:

typedef pair<const Key, T> value_type;

Internally, the elements in a map are always sorted by its key following a specific strict weak ordering criterion indicated by its internal comparison object (of type Compare).

map containers are generally slower than unordered_map containers to access individual elements by their key, but they allow the direct iteration on subsets based on their order.

The mapped values in a map can be accessed directly by their corresponding key using the bracket(方括号) operator ((operator[]).

Maps are typically implemented as binary search trees(二叉搜索树).

Container properties

  • Associative: Elements in associative containers are referenced by their key and not by their absolute position in the container.
  • Ordered: The elements in the container follow a strict order at all times. All inserted elements are given a position in this order.
  • Map: Each element associates a key to a mapped value: Keys are meant to identify the elements whose main content is the mapped value.
  • Unique keys: No two elements in the container can have equivalent keys.
  • Allocator-aware: The container uses an allocator object to dynamically handle its storage needs.

Template parameters

  • Key: Type of the keys. Each element in a map is uniquely identified by its key value. Aliased as member type map::key_type.
  • T: Type of the mapped value. Each element in a map stores some data as its mapped value. Aliased as member type map::mapped_type.
  • Compare: A binary predicate(二元谓词) that takes two element keys as arguments and returns a bool. The expression comp(a,b), where comp is an object of this type and a and b are key values, shall return true if a is considered to go before b in the strict weak ordering the function defines. The map object uses this expression to determine both the order the elements follow in the container and whether two element keys are equivalent (by comparing them reflexively: they are equivalent if !comp(a,b) && !comp(b,a)). No two elements in a map container can have equivalent keys. This can be a function pointer or a function object (see constructor for an example). This defaults to less, which returns the same as applying the less-than operator (a<b). Aliased as member type map::key_compare.
  • Alloc: Type of the allocator object used to define the storage allocation model. By default, the allocator class template is used, which defines the simplest memory allocation model and is value-independent. Aliased as member type map::allocator_type.

Member types

member type definition notes
key_type The first template parameter (Key)
mapped_type The second template parameter (T)
value_type pair<const key_type,mapped_type>
key_compare The third template parameter (Compare) defaults to: less<key_type>
value_compare Nested function class to compare elements see value_comp
allocator_type The fourth template parameter (Alloc) defaults to: allocator<value_type>
reference value_type&
const_reference const value_type&
pointer allocator_traits<allocator_type>::pointer for the default allocator: value_type*
const_pointer allocator_traits<allocator_type>::const_pointer for the default allocator: const value_type*
iterator a bidirectional iterator to value_type convertible to const_iterator
const_iterator a bidirectional iterator to const value_type
reverse_iterator reverse_iterator
const_reverse_iterator reverse_iterator<const_iterator>
difference_type a signed integral type, identical to:
iterator_traits::difference_type usually the same as ptrdiff_t
size_type an unsigned integral type that can represent any non-negative value of difference_type usually the same as size_t

Member functions

  • (constructor) Construct map (public member function )
  • (destructor) Map destructor (public member function )
  • operator= Copy container content (public member function )

Iterators:

  • begin: Return iterator to beginning (public member function )
  • end: Return iterator to end (public member function )
  • rbegin: Return reverse iterator to reverse beginning (public member function )
  • rend: Return reverse iterator to reverse end (public member function )
  • cbegin: Return const_iterator to beginning (public member function )
  • cend: Return const_iterator to end (public member function )
  • crbegin: Return const_reverse_iterator to reverse beginning (public member function )
  • crend: Return const_reverse_iterator to reverse end (public member function )

Capacity:

  • empty: Test whether container is empty (public member function )
  • size: Return container size (public member function )
  • max_size: Return maximum size (public member function )

Element access:

  • operator[]: Access element (public member function )
  • at: Access element (public member function )

Modifiers:

  • insert: Insert elements (public member function )
  • erase: Erase elements (public member function )
  • swap: Swap content (public member function )
  • clear: Clear content (public member function )
  • emplace: Construct and insert element (public member function )
  • emplace_hint: Construct and insert element with hint (public member function )

Observers(观察者):

  • key_comp: Return key comparison object (public member function )
  • value_comp: Return value comparison object (public member function )

Operations:

  • find: Get iterator to element (public member function )
  • count: Count elements with a specific key (public member function )
  • upper_bound: Return iterator to upper bound (public member function )
  • lower_bound: Return iterator to lower bound (public member function )
  • equal_range: Get range of equal elements (public member function )

Allocator:

  • get_allocator: Get allocator (public member function )

Code Example

  1. #include <iostream>
  2. #include <map>
  3. using namespace std;
  4. bool fncomp( char lhs, char rhs )
  5. { return lhs < rhs; }
  6. struct classcomp{
  7. bool operator() (const char& lhs, const char& rhs)
  8. { return lhs < rhs; }
  9. };
  10. int main(int argc, char **argv)
  11. {
  12. map<char,int> first1;
  13. first1['a'] = 10; first1['b'] = 20;
  14. first1['c'] = 30; first1['d'] = 40;
  15. map<char,int> first2( first1.begin(),first1.end() );
  16. map<char,int> first3( first2 );
  17. map<char,int, classcomp> first4; ///< class as Compare
  18. /** function pointer as Compare */
  19. bool(*fn_pt)(char,char) = fncomp;
  20. map<char,int,bool(*)(char,char)> first5(fn_pt);
  21. map<char,int> second;
  22. second.emplace('x', 100);
  23. second.emplace('y', 200);
  24. second.emplace('z', 300);
  25. cout << '\n';
  26. for(auto &x:second) cout << x.first << ":" << x.second << '\t';
  27. auto it = second.end();
  28. it = second.emplace_hint(it, 'b', 20);
  29. second.emplace_hint(it, 'a', 10);
  30. second.emplace_hint(it, 'c', 30);
  31. cout << '\n';
  32. for(auto &x:second) cout << x.first << ":" << x.second << '\t';
  33. map<char,int> third;
  34. /** 获取key 比较器 */
  35. map<char,int>::key_compare third_comp = third.key_comp();
  36. third['a'] = 100; third['b'] = 200;
  37. third['c'] = 300; third['d'] = 400;
  38. third['e'] = 500; third['f'] = 600;
  39. char dCh = 'd';
  40. it = third.begin();
  41. cout << '\n';
  42. do{
  43. cout << it->first << ":" << it->second << '\t';
  44. }while( third_comp( (*it++).first, dCh ) );
  45. pair<char,int> dValue = *third.rbegin();
  46. it = third.begin();
  47. cout << '\n';
  48. do{
  49. cout << it->first << ":" << it->second << '\t';
  50. }while( third.value_comp()( *it++, dValue ) );
  51. it = third.find('b');
  52. if( it != third.end() )
  53. third.erase(it);
  54. cout << '\n';
  55. for( char cIndex = 'a'; cIndex < 'z'; cIndex++ )
  56. {
  57. cout << cIndex;
  58. /** key == cIndex count */
  59. if( third.count(cIndex) > 0 )
  60. cout << " has \n";
  61. else
  62. cout << " not has.\n";
  63. }
  64. auto itlow = third.lower_bound('c'); ///< itlow points to c
  65. auto itup = third.upper_bound('e'); ///< itup points to f (not e)
  66. third.erase(itlow,itup);
  67. cout << '\n';
  68. for(auto &x:third) cout << x.first << ":" << x.second << '\t';
  69. map<char,int> four;
  70. four['a'] = 10; four['b'] = 20;
  71. four['c'] = 30; four['d'] = 40;
  72. four['e'] = 50; four['f'] = 60;
  73. pair< map<char,int>::iterator, map<char,int>::iterator > ret;
  74. ret = four.equal_range('b');
  75. cout << "\n lower bound points to:"
  76. << ret.first->first << ":" << ret.first->second;
  77. cout << "\n upper bound points to: "
  78. << ret.second->first << ":" << ret.second->second;
  79. return 0;
  80. }

Reference

cplusplus


C++ std::map的更多相关文章

  1. std::map用法

    STL是标准C++系统的一组模板类,使用STL模板类最大的好处就是在各种C++编译器上都通用.    在STL模板类中,用于线性数据存储管理的类主要有vector, list, map 等等.本文主要 ...

  2. C++ std::map::erase用法及其陷阱

    1.引入: STL的map中有一个erase方法用来从一个map中删除制定的节点 eg: map<string,string> mapTest; typedef map<string ...

  3. std::map

    1.例: map<int,string> m_mapTest; m_mapTest.insert(make_pair(1,"kong")); m_mapTest.ins ...

  4. std::map的clear()没有用?

    昨天晚上,我徒弟跑过来讲,他的程序的内存占用居高不下,愿意是std::map的clear()没有效果.于是我让他用erase(begin,end); 试试也不行. 代码如下: void release ...

  5. std::map的操作:插入、修改、删除和遍历

    using namespace std; std::map<int,int> m_map; 1.添加 for(int i=0;i<10;i++) { m_map.insert(mak ...

  6. Using std::map with a custom class key

    From: https://www.walletfox.com/course/mapwithcustomclasskey.php If you have ever tried to use a cus ...

  7. Std::map too few template arguments

    在上述的代码中,红色波浪线的部分编译的时候报错: error C2976: 'std::map' : too few template arguments 换成std::map<std::str ...

  8. 使用std::map和std::list存放数据,消耗内存比实际数据大得多

    使用std::map和std::list存放数据,消耗内存比实际数据大得多 场景:项目中需要存储一个结构,如下程序段中TEST_DATA_STRU,结构占24B.但是使用代码中的std::list&l ...

  9. STL之std::set、std::map的lower_bound和upper_bound函数使用说明

    由于在使用std::map时感觉lower_bound和upper_bound函数了解不多,这里整理并记录下相关用法及功能. STL的map.multimap.set.multiset都有三个比较特殊 ...

随机推荐

  1. Hadoop 中利用 mapreduce 读写 mysql 数据

    Hadoop 中利用 mapreduce 读写 mysql 数据   有时候我们在项目中会遇到输入结果集很大,但是输出结果很小,比如一些 pv.uv 数据,然后为了实时查询的需求,或者一些 OLAP ...

  2. 使用CSS3实现一个3D相册

    CSS3系列我已经写过两篇文章,感兴趣的同学可以先看一下CSS3初体验之奇技淫巧,CSS3 3D立方体效果-transform也不过如此 第一篇主要列出了一些常用或经典的CSS3技巧和方法:第二篇是一 ...

  3. SuperMap iClient for JavaScript 新手入门

    地理信息系统(英语:Geographic Information System,缩写:GIS)是一门综合性学科,结合地理学与地图学,已经广泛的应用在不同的领域,是用于输入.存储.查询.分析和显示地理数 ...

  4. 浅谈 LayoutInflater

    浅谈 LayoutInflater 版权声明:本文为博主原创文章,未经博主允许不得转载. 微博:厉圣杰 源码:AndroidDemo/View 文中如有纰漏,欢迎大家留言指出. 在 Android 的 ...

  5. 如何利用ansible callback插件对执行结果进行解析

    最近在写一个批量巡检工具,利用ansible将脚本推到各个机器上执行,然后将执行的结果以json格式返回来. 如下所示: # ansible node2 -m script -a /root/pyth ...

  6. Response.Redirect引起的性能问题分析

    现象: 最近做的一个系统通过单点登录(SSO) 技术验证用户登录.用户在SSO 系统上通过验证后,跳转到该系统的不同模块.而跳转的时间一直维持子啊几分钟左右. 分析步骤: 在问题复现时抓取Hang d ...

  7. 负载均衡——nginx理论

     nginx是什么? nginx是一个强大的web服务器软件,用于处理高并发的http请求和作为反向代理服务器做负载均衡.具有高性能.轻量级.内存消耗少,强大的负载均衡能力等优势.  nginx架构? ...

  8. 【转】 FineBI:自助式BI工具打造业务分析的“快与准”

    如今的企业经营方式,业务对于数据分析有极大的需求,但却苦于没有数据以及工具的有效支持,业务分析仍就依赖于IT报表制作.而IT方不断地按业务需求去调研.确认业务逻辑,然后取数做报表,其中还要忍受业务的需 ...

  9. angular2之前端篇—1(node服务器分支)

    上一篇.net core和angular2之前端篇-1 使用的是dotnet模板.之所以用它,因为想用他写webapi,但是写道下一篇的时候遇到点问题,所以先写个分支测试一下.这次是用Node作为服务 ...

  10. android SystemServer.java启动的服务。

    EntropyService:熵(shang)服务,用于产生随机数PowerManagerService:电源管理服务ActivityManagerService:最核心服务之一,Activity管理 ...