C++ std::map
std::map
template < class Key, // map::key_type
class T, // map::mapped_type
class Compare = less<Key>, // map::key_compare
class Alloc = allocator<pair<const Key,T> > // map::allocator_type
> 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
#include <iostream>
#include <map>
using namespace std;
bool fncomp( char lhs, char rhs )
{ return lhs < rhs; }
struct classcomp{
bool operator() (const char& lhs, const char& rhs)
{ return lhs < rhs; }
};
int main(int argc, char **argv)
{
map<char,int> first1;
first1['a'] = 10; first1['b'] = 20;
first1['c'] = 30; first1['d'] = 40;
map<char,int> first2( first1.begin(),first1.end() );
map<char,int> first3( first2 );
map<char,int, classcomp> first4; ///< class as Compare
/** function pointer as Compare */
bool(*fn_pt)(char,char) = fncomp;
map<char,int,bool(*)(char,char)> first5(fn_pt);
map<char,int> second;
second.emplace('x', 100);
second.emplace('y', 200);
second.emplace('z', 300);
cout << '\n';
for(auto &x:second) cout << x.first << ":" << x.second << '\t';
auto it = second.end();
it = second.emplace_hint(it, 'b', 20);
second.emplace_hint(it, 'a', 10);
second.emplace_hint(it, 'c', 30);
cout << '\n';
for(auto &x:second) cout << x.first << ":" << x.second << '\t';
map<char,int> third;
/** 获取key 比较器 */
map<char,int>::key_compare third_comp = third.key_comp();
third['a'] = 100; third['b'] = 200;
third['c'] = 300; third['d'] = 400;
third['e'] = 500; third['f'] = 600;
char dCh = 'd';
it = third.begin();
cout << '\n';
do{
cout << it->first << ":" << it->second << '\t';
}while( third_comp( (*it++).first, dCh ) );
pair<char,int> dValue = *third.rbegin();
it = third.begin();
cout << '\n';
do{
cout << it->first << ":" << it->second << '\t';
}while( third.value_comp()( *it++, dValue ) );
it = third.find('b');
if( it != third.end() )
third.erase(it);
cout << '\n';
for( char cIndex = 'a'; cIndex < 'z'; cIndex++ )
{
cout << cIndex;
/** key == cIndex count */
if( third.count(cIndex) > 0 )
cout << " has \n";
else
cout << " not has.\n";
}
auto itlow = third.lower_bound('c'); ///< itlow points to c
auto itup = third.upper_bound('e'); ///< itup points to f (not e)
third.erase(itlow,itup);
cout << '\n';
for(auto &x:third) cout << x.first << ":" << x.second << '\t';
map<char,int> four;
four['a'] = 10; four['b'] = 20;
four['c'] = 30; four['d'] = 40;
four['e'] = 50; four['f'] = 60;
pair< map<char,int>::iterator, map<char,int>::iterator > ret;
ret = four.equal_range('b');
cout << "\n lower bound points to:"
<< ret.first->first << ":" << ret.first->second;
cout << "\n upper bound points to: "
<< ret.second->first << ":" << ret.second->second;
return 0;
}
Reference
C++ std::map的更多相关文章
- std::map用法
STL是标准C++系统的一组模板类,使用STL模板类最大的好处就是在各种C++编译器上都通用. 在STL模板类中,用于线性数据存储管理的类主要有vector, list, map 等等.本文主要 ...
- C++ std::map::erase用法及其陷阱
1.引入: STL的map中有一个erase方法用来从一个map中删除制定的节点 eg: map<string,string> mapTest; typedef map<string ...
- std::map
1.例: map<int,string> m_mapTest; m_mapTest.insert(make_pair(1,"kong")); m_mapTest.ins ...
- std::map的clear()没有用?
昨天晚上,我徒弟跑过来讲,他的程序的内存占用居高不下,愿意是std::map的clear()没有效果.于是我让他用erase(begin,end); 试试也不行. 代码如下: void release ...
- std::map的操作:插入、修改、删除和遍历
using namespace std; std::map<int,int> m_map; 1.添加 for(int i=0;i<10;i++) { m_map.insert(mak ...
- 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 ...
- Std::map too few template arguments
在上述的代码中,红色波浪线的部分编译的时候报错: error C2976: 'std::map' : too few template arguments 换成std::map<std::str ...
- 使用std::map和std::list存放数据,消耗内存比实际数据大得多
使用std::map和std::list存放数据,消耗内存比实际数据大得多 场景:项目中需要存储一个结构,如下程序段中TEST_DATA_STRU,结构占24B.但是使用代码中的std::list&l ...
- STL之std::set、std::map的lower_bound和upper_bound函数使用说明
由于在使用std::map时感觉lower_bound和upper_bound函数了解不多,这里整理并记录下相关用法及功能. STL的map.multimap.set.multiset都有三个比较特殊 ...
随机推荐
- 【原】Android热更新开源项目Tinker源码解析系列之二:资源文件热更新
上一篇文章介绍了Dex文件的热更新流程,本文将会分析Tinker中对资源文件的热更新流程. 同Dex,资源文件的热更新同样包括三个部分:资源补丁生成,资源补丁合成及资源补丁加载. 本系列将从以下三个方 ...
- ASP.NET_各个币种之间的汇率转换(实时)使用Yahoo汇率。
近期开发支付平台的时候有运用到各国的实时汇率之间的转换问题,于是在往上找了很多相关资料,以下就是一些参考网址: 1.提供API接口的网站:https://www.showapi.com:这个网站有提供 ...
- ASP.NET Core 1.1.0 Release Notes
ASP.NET Core 1.1.0 Release Notes We are pleased to announce the release of ASP.NET Core 1.1.0! Antif ...
- java基础_集合List与Set接口
List接口继承了Collection的方法 当然也有自己特有的方法向指定位置添加元素 add(索引,添加的元素); 移除指定索引的元素 remove(索引) 修改指定索引的元素 set ...
- JavaScript模仿块级作用域
avaScript 没有块级作用域的概念.这意味着在块语句中定义的变量,实际上是在包含函数中而非语句中创建的,来看下面的例子: function outputNumbers(count){ for ( ...
- Smarty的基本使用与总结
含义: Smarty是PHP的一个引擎模板,可以更好的进行逻辑与显示的分离,即我们常说的MVC,这个引擎的作用就是将C分离出来. 环境需求:PHP5.2或者更高版本 我使用的环境是:PHP5.3,wi ...
- 阿里云服务器上配置并使用: PHP + Redis + Mysql 从配置到使用
(原创出处为本博客,http://www.cnblogs.com/linguanh/) 目录: 一,下载 二,解压 三,配置与启动 四,测试 Redis 五,配置 phpRedis 扩展 六,综合测试 ...
- VS2015在创建项目时的一些注意事项
一.下面是在创建一个新的项目是我最常用的,现在对他们一一做一个详细的介绍: 1.Win32控制台应用程序我平时编写小的C/C++程序都用它,它应该是用的最多的. 2.名称和解决方案名称的区别:名称是项 ...
- ASP.NET MVC关于Ajax以及Jquery的无限级联动
---恢复内容开始--- 第一次发表博文,发表博文的目的是巩固自己的技术,也能够共享给大家.写的不好的地方,希望大家多给给意见.老司机勿喷 数据结构() NewsTypeId 新闻ID, NewsTy ...
- 浅谈SQL注入风险 - 一个Login拿下Server
前两天,带着学生们学习了简单的ASP.NET MVC,通过ADO.NET方式连接数据库,实现增删改查. 可能有一部分学生提前预习过,在我写登录SQL的时候,他们鄙视我说:“老师你这SQL有注入,随便都 ...