来源:http://blog.csdn.net/wallwind/article/details/6876892
 

map<Key, Data, Compare, Alloc>

map是一种关联容器,存储相结合形成的一个关键值和映射值的元素。Map 是一种Pair Associative Container,意味着它的值类型为 pair<const Key, Data>. 而且也是 Unique Associative Container, 也就是任何两个元素没有相同的key值。

map具有重要的属性,就是在map对象中插入一个新元素不指向现有元素的迭代器失效。从map上删除一个元素,也没有任何迭代器失效,除非,当然,实际上指向正在被删除的元素的迭代器。

1、例子

  1. struct ltstr
  2. {
  3. bool operator()(const char* s1, const char* s2) const
  4. {
  5. return strcmp(s1, s2) < 0;
  6. }
  7. };
  8. int main()
  9. {
  10. map<const char*, int, ltstr> months;
  11. months["january"] = 31;
  12. months["february"] = 28;
  13. months["march"] = 31;
  14. months["april"] = 30;
  15. months["may"] = 31;
  16. months["june"] = 30;
  17. months["july"] = 31;
  18. months["august"] = 31;
  19. months["september"] = 30;
  20. months["october"] = 31;
  21. months["november"] = 30;
  22. months["december"] = 31;
  23. cout << "june -> " << months["june"] << endl;
  24. map<const char*, int, ltstr>::iterator cur  = months.find("june");
  25. map<const char*, int, ltstr>::iterator prev = cur;
  26. map<const char*, int, ltstr>::iterator next = cur;
  27. ++next;
  28. --prev;
  29. cout << "Previous (in alphabetical order) is " << (*prev).first << endl;
  30. cout << "Next (in alphabetical order) is " << (*next).first << endl;
  31. }

2、定义形式

  1. template < class Key, class T, class Compare = less<Key>,
  2. class Allocator = allocator<pair<const Key,T> > > class map;

3、模板参数具有以下涵义:

key:关键值的类型。在map对象中的每个元素是通过该关键值唯一确定元素的。
T:映射值的类型。在map中的每个元素是用来储存一些数据作为其映射值。
compare:Comparison类:A类键的类型,它有两个参数,并返回一个bool。表达comp(A,B),comp是这比较类A和B是关键值的对象,应返回true,如果是在早先的立场比B放置在一个严格弱排序操作。这可以是一个类实现一个函数调用运算符或一个函数的指针(见一个例子构造)。默认的对于<KEY>,返回申请小于操作符相同的默认值(A <B)。
Map对象使用这个表达式来确定在容器中元素的位置。以下这个规则在任何时候都排列在map容器中的所有元素。
Allocator:用于定义存储分配模型分配器对象的类型。默认情况下,分配器类模板,它定义了最简单的内存分配模式,是值独立的

  1. map<Key,T>::iterator it;
  2. (*it).first;             // 指向key值(of type Key)
  3. (*it).second;            // 映射的值(of type T)
  4. (*it);                   // the "element value" (of type pair<const Key,T>)    //看到此处懵逼啊有木有!!(*it)到底该如何表述,查CPLUSPLUS  pair  如下:
  5. -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  6. class template
  7. <utility>
  8. std::pair
  9. template <class T1, class T2> struct pair;
    Pair of values

    This class couples together a pair of values, which may be of different types (T1 and T2). The individual values can be accessed through its public members first and second.  是一对值

    Pairs are a particular case of tuple.    pairs是一特定的元祖,然后我搜了tuple,

  10. class template
    <tuple>

    std::tuple

    template <class... Types> class tuple;
    Tuple

    A tuple is an object capable to hold a collection of elements. Each element can be of a different type.   tuple是一个能够容纳元素集合的obiect。每个元素可以是不同的类型。

  11. it本身是迭代器, (*it)默认指迭代器内部第一个键值对(tuple元组)    //尼玛,看半天才知道此处专业叫法是迭代器里边的‘解引用操作符’,指向其内部元素!!

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
也可以如下表达:

  1. it->first;               // same as (*it).first   (the key value)
  2. it->second;              // same as (*it).second  (the mapped value)

4、成员变量和成员函数

Member Where defined Description
key_type Associative Container map中的key类型
data_type Pair Associative Container key关联的值类型
value_type Pair Associative Container 对象类型, pair<const key_type, data_type>,存储在map中
key_compare Sorted Associative Container Function object 通过顺序比较
value_compare Sorted Associative Container Function object that compares two values for ordering.
pointer Container Pointer to T.
reference Container Reference to T
const_reference Container Const reference to T
size_type Container An unsigned integral type.
difference_type Container A signed integral type.
iterator Container Iterator used to iterate through a map[1]
const_iterator Container Const iterator used to iterate through a map.
reverse_iterator Reversible Container Iterator used to iterate backwards through a map.[1]
const_reverse_iterator Reversible Container Const iterator used to iterate backwards through amap.
iterator begin() Container Returns an iterator pointing to the beginning of the map.
iterator end() Container Returns an iterator pointing to the end of the map.
const_iterator begin() const Container Returns a const_iterator pointing to the beginning of themap.
const_iterator end() const Container Returns a const_iterator pointing to the end of the map.
reverse_iterator rbegin() Reversible Container Returns a reverse_iterator pointing to the beginning of the reversed map.
reverse_iterator rend() Reversible Container Returns a reverse_iterator pointing to the end of the reversed map.
const_reverse_iterator rbegin() const Reversible Container Returns a const_reverse_iterator pointing to the beginning of the reversed map.
const_reverse_iterator rend() const Reversible Container Returns a const_reverse_iterator pointing to the end of the reversed map.
size_type size() const Container Returns the size of the map.
size_type max_size() const Container Returns the largest possible size of the map.
bool empty() const Container true if the map's size is 0.
key_compare key_comp() const Sorted Associative Container Returns the key_compare object used by the map.
value_compare value_comp() const Sorted Associative Container Returns the value_compare object used by the map.
map() Container Creates an empty map.
map(const key_compare& comp) Sorted Associative Container Creates an empty map, using comp as thekey_compare object.
template <class InputIterator>
map(InputIterator f, InputIterator l)
Unique Sorted Associative Container Creates a map with a copy of a range.
template <class InputIterator>
map(InputIterator f, InputIterator l,
const key_compare& comp)
Unique Sorted Associative Container Creates a map with a copy of a range, using compas thekey_compare object.
map(const map&) Container The copy constructor.
map& operator=(const map&) Container The assignment operator
void swap(map&) Container Swaps the contents of two maps.
pair<iterator, bool>
insert(const value_type& x)
Unique Associative Container Inserts x into the map.
iterator insert(iterator pos,
const value_type& x)
Unique Sorted Associative Container Inserts x into the map, using pos as a hint to where it will be inserted.
template <class InputIterator>
void insert(InputIterator, InputIterator)
[2]
Unique Sorted Associative Container Inserts a range into the map.
void erase(iterator pos) Associative Container Erases the element pointed to by pos.
size_type erase(const key_type& k) Associative Container Erases the element whose key is k.
void erase(iterator first, iterator last) Associative Container Erases all elements in a range.
void clear() Associative Container Erases all of the elements.
iterator find(const key_type& k) Associative Container Finds an element whose key is k.
const_iterator find(const key_type& k) const Associative Container Finds an element whose key is k.
size_type count(const key_type& k) Unique Associative Container Counts the number of elements whose key is k.
iterator lower_bound(const key_type& k) Sorted Associative Container Finds the first element whose key is not less thank.
const_iterator lower_bound(const key_type& k) const Sorted Associative Container Finds the first element whose key is not less thank.
iterator upper_bound(const key_type& k) Sorted Associative Container Finds the first element whose key greater than k.
const_iterator upper_bound(const key_type& k) const Sorted Associative Container Finds the first element whose key greater than k.
pair<iterator, iterator>
equal_range(const key_type& k)
Sorted Associative Container Finds a range containing all elements whose key isk.
pair<const_iterator, const_iterator>
equal_range(const key_type& k) const
Sorted Associative Container Finds a range containing all elements whose key isk.
data_type&
operator[](const key_type& k) [3]
map See below.
bool operator==(const map&,
const map&)
Forward Container Tests two maps for equality. This is a global function, not a member function.
bool operator<(const map&,
const map&)
Forward Container Lexicographical comparison. This is a global function, not a member function.
  1. 下面展示了常用的一些方法。<p>// stu_map.cpp : 定义控制台应用程序的入口点。
  2. //
  3. #include "stdafx.h"
  4. #include <iostream>
  5. #include <map>
  6. using namespace std;
  7. bool fncomp(char lhs,char rhs)
  8. {
  9. return lhs<rhs;
  10. }
  11. struct classcomp
  12. {
  13. bool operator()(const char& lhs,const char& rhs)
  14. {
  15. return lhs<rhs;
  16. }
  17. };
  18. int _tmain(int argc, _TCHAR* argv[])
  19. {
  20. map<char,int> mymap;
  21. mymap['a']=10;
  22. mymap['b']=60;
  23. mymap['c']=30;
  24. mymap['d']=90;
  25. mymap['e']=50;
  26. map<char,int> second(mymap);
  27. map<char,int> third(mymap.begin(),mymap.end());
  28. map<char,int,classcomp> fourth;
  29. bool(*fn_pt)(char,char)=fncomp;
  30. map<char,int,bool(*)(char,char)> fifth(fn_pt);
  31. map<char,int>::key_compare key_comp;
  32. map<char,int>::iterator it;
  33. it=mymap.begin();
  34. for (it;it!=mymap.end();it++)
  35. {
  36. cout<<it->first<<":"<<it->second<<endl;
  37. }
  38. cout<<"================================="<<endl;
  39. second.clear();
  40. second['a']=1002;
  41. second['b']=10023;
  42. while (!second.empty())
  43. {
  44. cout << second.begin()->first << " => ";
  45. cout << second.begin()->second << endl;
  46. second.erase(second.begin());
  47. }
  48. cout<<"================================="<<endl;
  49. mymap.insert(pair<char,int>('f',100) );
  50. mymap.insert(pair<char,int>('g',200) );
  51. cout<<"f => " <<mymap.find('f')->second<<endl;
  52. cout<<"g => " <<mymap.find('g')->second<<endl;
  53. cout<<"================================="<<endl;
  54. key_comp=mymap.key_comp();
  55. cout << "mymap contains:\n";
  56. char highest=mymap.rbegin()->first;     // key value of last element
  57. it=mymap.begin();
  58. do {
  59. cout << (*it).first << " => " << (*it).second << endl;
  60. } while ( key_comp((*it++).first, highest) );
  61. cout << endl;
  62. return 0;
  63. }
  64. </p>

运行结果:

C++中map的概念,与简单操作的更多相关文章

  1. MongoDB快速入门学习笔记2 MongoDB的概念及简单操作

    1.以下列举普通的关系型数据库和MongoDB数据库简单概念上的区别: 关系型数据库 MongoDB数据库 说明 database database 数据库 table collection 数据库表 ...

  2. MySQL基本概念以及简单操作

    一.MySQL   MySQL是一个关系型数据库管理系统,由瑞典MySQL AB 公司开发,目前属于Oracle 旗下产品.MySQL 是最流行的关系型数据库管理系统之一,在 WEB 应用方面,MyS ...

  3. matlab中矩阵的表示与简单操作

    原文地址为:matlab矩阵的表示和简单操作 一.矩阵的表示在MATLAB中创建矩阵有以下规则: a.矩阵元素必须在”[ ]”内: b.矩阵的同行元素之间用空格(或”,”)隔开: c.矩阵的行与行之间 ...

  4. epoll、mysql概念及简单操作

    epoll 程序阻塞的过程 假设我们目前运行了三个进程A B C ,如果他们都在处于运行态,那就会被加到一个运行队列中 进程A正在运行socket程序 在linux中有句话,万物皆文件,socket对 ...

  5. Java中Arrays 与 Collections 的简单操作

    import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.C ...

  6. C++中Map的使用 (个人简单的对于String的使用)

    #include<map> #include<iostream> #include<string> using namespace std; int main() ...

  7. 关于CSS格式与布局中的基础知识的简单操作

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  8. JS Map 和 List 的简单实现代码

    javascript中是没有map和list 结构的. 本篇文章是对在JS中Map和List的简单实现代码进行了详细的分析介绍,需要的朋友参考下 代码如下: /* * MAP对象,实现MAP功能 *  ...

  9. C++ STL中Map的相关排序操作:按Key排序和按Value排序 - 编程小径 - 博客频道 - CSDN.NET

    C++ STL中Map的相关排序操作:按Key排序和按Value排序 - 编程小径 - 博客频道 - CSDN.NET C++ STL中Map的相关排序操作:按Key排序和按Value排序 分类: C ...

随机推荐

  1. struct2cell

    函数功能:把结构体转换为元胞数组. 语法格式: c = struct2cell(s) 如果s是m*n(m行n列)的二维的结构体数组,每个结构体含有p个域,则转换得到一个p*m*n的元胞数组c. 如果s ...

  2. html:关于表单功能的学习

    比如我在某jsp页面中写了如下表单: <form action="/MavenWeb/TestFormPost" method="get">   & ...

  3. LeetCode:Pascal's Triangle I II

    LeetCode:Pascal's Triangle Given numRows, generate the first numRows of Pascal's triangle. For examp ...

  4. iOS开发UI篇—popoverController简单介绍(ipad)

    一.简单介绍 1.什么是UIPopoverController 是iPad开发中常见的一种控制器(在iPhone上不允许使用) 跟其他控制器不一样的是,它直接继承自NSObject,并非继承自UIVi ...

  5. ASP.NET MVC 5 入门教程 (1) 新建项目

    文章来源: Slark.NET-博客园 http://www.cnblogs.com/slark/p/mvc-5-get-started-create-project.html 下一节:ASP.NET ...

  6. IText&Html2canvas js截图 绘制 导出PDF

    Html2canvas JS截图 HTML <div id="divPDF"> 需要截图的区域 </div> JS <script src=" ...

  7. SQL脚本循环修改数据库字段类型

    数据库在设计的时候也许考虑不全面,导致某些字段类型不太准确.比如设计的时候是varchar(1024),但是实际使用的时候却发现太小了,装不下,于是需要修改字段类型为ntext什么的. 我最近就遇到了 ...

  8. Android Studio导入Eclipse项目和一些常见的问题

    Android Studio版本 Eclipse项目工程:一个主工程,一个Emojicon依赖库. 有两种方式导入Eclipse工程: 1.兼容Eclipse 2.全新的Android Gradle ...

  9. 好玩的Prim算法

    这段时间学算法,用JS实现了一个Prim,用于在连通图中找出最小树,具体内容.代码解析周末会不上,现在先把源码献上: <!DOCTYPE html> <html charset='G ...

  10. DOM(五)事件对象

    浏览器中的事件都是以对象的形式存在的,同样ie浏览器与标准dom浏览器之间存在获取事件对象上也存在差别.在ie浏览器中事件对象是windows对象的一个属性event,访问通常采用如下方法. oP.o ...