map是键-值对的集合
template < class Key, class T, class Compare = less<Key>,
class Allocator = allocator<pair<const Key,T> > > class map;
key:关键值的类型。在map对象中的每个元素是通过该关键值唯一确定元素的。
T:映射值的类型。在map中的每个元素是用来储存一些数据作为其映射值。
Compare 就是构建红黑树时用到的比较方法,判断节点存储位置,默认less(小于)
Alloc 则是内存配置器啦,默认alloc
map 关联容器(key-value对应),set 关联容器( 集合) 默认不能重复
multimap 同map,multiset同set,只是允许重复
SGI STL 中 这四种容器 都是用 RH-tree红黑树构造的(vector封装数组,list封装了链表,map和 set封装了二叉树)
SGI STL 根据hashtable的特性,又实现了 hash_map,hash_set,hash_multimap,hash_multiset 四种对应的容器都是以hashtable作为底层容器实现的
怎样统计单词出现的频率
#include <cstdlib>
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main(int argc, char *argv[])
{
string s;
map<string,int> counters;
while(cin>>s){
if(s=="exit1") break;
++counters[s];
}
for(map<string,int>::const_iterator it=counters.begin();it!=counters.end();++it){
cout<<it->first<<"\t"<<it->second<<endl;
}
system("PAUSE");
return EXIT_SUCCESS;
}
/*
my name is wang wei wei
your name is wang wei wei
good
i like it is
exit1
good 1
i 1
is 3
it 1
like 1
my 1
name 2
wang 2
wei 4
your 1
*/
MAP插入数据
mapStudent.insert(pair<int, string>(1, “student_one”));
mapStudent.insert(map<int, string>::value_type (2, “student_two”));
mapStudent[3] = “student_three”; // 可以覆盖
判断是否插入成功
Pair<map<int, string>::iterator, bool> Insert_Pair;
Insert_Pair = mapStudent.insert(pair<int, string>(1, “student_one”));
If(Insert_Pair.second == true)
{
Cout<<”Insert Successfully”<<endl;
}
Else
{
Cout<<”Insert Failure”<<endl;