C++STL之map学习

map<Key, Data, Compare, Alloc>

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

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

1、例子

struct ltstr { bool operator()(const char* s1, const char* s2) const { return strcmp(s1, s2) < 0; } }; int main() { map<const char*, int, ltstr> months; months["january"] = 31; months["february"] = 28; months["march"] = 31; months["april"] = 30; months["may"] = 31; months["june"] = 30; months["july"] = 31; months["august"] = 31; months["september"] = 30; months["october"] = 31; months["november"] = 30; months["december"] = 31; cout << "june -> " << months["june"] << endl; map<const char*, int, ltstr>::iterator cur = months.find("june"); map<const char*, int, ltstr>::iterator prev = cur; map<const char*, int, ltstr>::iterator next = cur; ++next; --prev; cout << "Previous (in alphabetical order) is " << (*prev).first << endl; cout << "Next (in alphabetical order) is " << (*next).first << endl; }

2、定义形式

template < class Key, class T, class Compare = less<Key>, 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:用于定义存储分配模型分配器对象的类型。默认情况下,分配器类模板,它定义了最简单的内存分配模式,是值独立的

map<Key,T>::iterator it; (*it).first; // 指向key值(of type Key) (*it).second; // 映射的值(of type T) (*it); // the "element value" (of type pair<const Key,T>)


也可以如下表达:

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


4、成员变量和成员函数

MemberWhere definedDescription
key_typeAssociative Containermap中的key类型
data_typePair Associative Containerkey关联的值类型
value_typePair Associative Container对象类型, pair<const key_type, data_type>,存储在map中
key_compareSorted Associative Container Function object 通过顺序比较
value_compareSorted Associative Container Function object that compares two values for ordering.
pointerContainerPointer to T.
referenceContainerReference to T
const_referenceContainerConst reference to T
size_typeContainerAn unsigned integral type.
difference_typeContainerA signed integral type.
iteratorContainerIterator used to iterate through a map. [1]
const_iteratorContainerConst iterator used to iterate through a map.
reverse_iteratorReversible ContainerIterator used to iterate backwards through a map. [1]
const_reverse_iteratorReversible ContainerConst iterator used to iterate backwards through a map.
iterator begin()ContainerReturns an iterator pointing to the beginning of the map.
iterator end()ContainerReturns an iterator pointing to the end of the map.
const_iterator begin() constContainerReturns a const_iterator pointing to the beginning of themap.
const_iterator end() constContainerReturns a const_iterator pointing to the end of the map.
reverse_iterator rbegin()Reversible ContainerReturns a reverse_iterator pointing to the beginning of the reversed map.
reverse_iterator rend()Reversible ContainerReturns a reverse_iterator pointing to the end of the reversed map.
const_reverse_iterator rbegin() constReversible ContainerReturns a const_reverse_iterator pointing to the beginning of the reversed map.
const_reverse_iterator rend() constReversible ContainerReturns a const_reverse_iterator pointing to the end of the reversed map.
size_type size() constContainerReturns the size of the map.
size_type max_size() constContainerReturns the largest possible size of the map.
bool empty() constContainer true if the map's size is 0.
key_compare key_comp() constSorted Associative ContainerReturns the key_compare object used by the map.
value_compare value_comp() constSorted Associative ContainerReturns the value_compare object used by the map.
map()ContainerCreates an empty map.
map(const key_compare& comp)Sorted Associative ContainerCreates an empty map, using comp as the key_compare object.
template <class InputIterator>
map(InputIterator f, InputIterator l)
Unique Sorted Associative ContainerCreates a map with a copy of a range.
template <class InputIterator>
map(InputIterator f, InputIterator l,
    const key_compare& comp)
Unique Sorted Associative ContainerCreates a map with a copy of a range, using comp as thekey_compare object.
map(const map&)ContainerThe copy constructor.
map& operator=(const map&)ContainerThe assignment operator
void swap(map&)ContainerSwaps the contents of two maps.
pair<iterator, bool>
insert(const value_type& x)
Unique Associative ContainerInserts x into the map.
iterator insert(iterator pos,
                const value_type& x)
Unique Sorted Associative ContainerInserts 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 ContainerInserts a range into the map.
void erase(iterator pos)Associative ContainerErases the element pointed to by pos.
size_type erase(const key_type& k)Associative ContainerErases the element whose key is k.
void erase(iterator first, iterator last)Associative ContainerErases all elements in a range.
void clear()Associative ContainerErases all of the elements.
iterator find(const key_type& k)Associative ContainerFinds an element whose key is k.
const_iterator find(const key_type& k) constAssociative ContainerFinds an element whose key is k.
size_type count(const key_type& k)Unique Associative ContainerCounts the number of elements whose key is k.
iterator lower_bound(const key_type& k)Sorted Associative ContainerFinds the first element whose key is not less than k.
const_iterator lower_bound(const key_type& k) constSorted Associative ContainerFinds the first element whose key is not less than k.
iterator upper_bound(const key_type& k)Sorted Associative ContainerFinds the first element whose key greater than k.
const_iterator upper_bound(const key_type& k) constSorted Associative ContainerFinds the first element whose key greater than k.
pair<iterator, iterator> 
equal_range(const key_type& k)
Sorted Associative ContainerFinds a range containing all elements whose key is k.
pair<const_iterator, const_iterator> 
equal_range(const key_type& k) const
Sorted Associative ContainerFinds a range containing all elements whose key is k.
data_type& 
operator[](const key_type& k) [3]
mapSee below.
bool operator==(const map&, 
                const map&)
Forward ContainerTests two maps for equality. This is a global function, not a member function.
bool operator<(const map&, 
               const map&)
Forward ContainerLexicographical comparison. This is a global function, not a member function.
下面展示了常用的一些方法。

// stu_map.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #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 _tmain(int argc, _TCHAR* argv[]) { map<char,int> mymap; mymap['a']=10; mymap['b']=60; mymap['c']=30; mymap['d']=90; mymap['e']=50; map<char,int> second(mymap); map<char,int> third(mymap.begin(),mymap.end()); map<char,int,classcomp> fourth; bool(*fn_pt)(char,char)=fncomp; map<char,int,bool(*)(char,char)> fifth(fn_pt); map<char,int>::key_compare key_comp; map<char,int>::iterator it; it=mymap.begin(); for (it;it!=mymap.end();it++) { cout<<it->first<<":"<<it->second<<endl; } cout<<"================================="<<endl; second.clear(); second['a']=1002; second['b']=10023; while (!second.empty()) { cout << second.begin()->first << " => "; cout << second.begin()->second << endl; second.erase(second.begin()); } cout<<"================================="<<endl; mymap.insert(pair<char,int>('f',100) ); mymap.insert(pair<char,int>('g',200) ); cout<<"f => " <<mymap.find('f')->second<<endl; cout<<"g => " <<mymap.find('g')->second<<endl; cout<<"================================="<<endl; key_comp=mymap.key_comp(); cout << "mymap contains:\n"; char highest=mymap.rbegin()->first; // key value of last element it=mymap.begin(); do { cout << (*it).first << " => " << (*it).second << endl; } while ( key_comp((*it++).first, highest) ); cout << endl; return 0; }


运行结果:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值