Chapter 15.關聯容器map

map簡介

map是一個關聯容器,map中的每一個值是一個由key value和一個mapped value組成的,通過key value來索引mapped value,以便有效的訪問mapped value

在內部,map裏的元素總是以從低到高的一個特定的嚴格的弱序標準排序
map的特點
1.在同一個map中key value是唯一的
2.元素值由key value和mapped value組成,以key value作爲索引來訪問
3.在map容器中元素總是是以弱序排序
4.支持雙向迭代器
5.map支持直接存取操作符operator[]
6.map的每個數據對應紅黑樹上的一個節點,這個節點在不保存你的數據時一個父節點指針,左右孩子指針,還有一個枚舉值(標示紅黑的,相當於平衡二叉樹中的平衡因子),是佔用4+2*4+4=16個字節的

map模板

template < class Key, class T, class Compare = less<Key>,

           class Allocator = allocator<pair<const Key,T> > > class map;
Construct
1.explicit map ( const Compare& comp = Compare(),
               const Allocator& = Allocator() );
2.template <class InputIterator>
    map ( InputIterator first, InputIterator last,
        const Compare& comp = Compare(), const Allocator& = Allocator() );
3.map ( const map<Key,T,Compare,Allocator>& x );

eg:
bool fncomp (char lhs, char rhs) {return lhs<rhs;}
struct classcomp {
  bool operator() (const char& lhs, const char& rhs) const
  {return lhs<rhs;}
};
int main ()
{
  map<char,int> first;
  first['a']=10;
  first['b']=30;
  first['c']=50;
  first['d']=70;
  map<char,int> second (first.begin(),first.end());
  map<char,int> third (second);
  map<char,int,classcomp> fourth;                 // class as Compare
  bool(*fn_pt)(char,char) = fncomp;
  map<char,int,bool(*)(char,char)> fifth (fn_pt); // function pointer as Compare
  return 0;
}
Capacity:

empty Test whether container is empty
size Return container size
max_size Return maximum size
Element access:

operator[] Access element
Modifiers:

insert Insert element 
erase Erase elements
swap Swap content
clear Clear content
//insert
1.pair<iterator,bool> insert ( const value_type& x );
2.iterator insert ( iterator position, const value_type& x );
3.template <class InputIterator>
               void insert ( InputIterator first, InputIterator last );

eg://四種insert方式
typedef map<int,string,less<int>> mapType;
void printMap(mapType::iterator begin,mapType::iterator end);
int main()
{
  mapType m;
  //1.make_pair<>()
  std::map<std::string,float> coll;
  coll.insert(std::make_pair("otto",22.3));
  //2.pair<>()
  m.insert(pair<int,string>(1,"hello"));
  m.insert(pair<int,string>(2,"world"));
  printMap(m.begin(),m.end());
  //3.value_type()
  m.insert(mapType::value_type(3,"!"));
  printMap(m.begin(),m.end());
  pair<mapType::iterator,bool> flag = m.insert(mapType::value_type(3,"222"));
  if (flag.second)
  {
    cout << "insert success" << endl;
  }
  else
  {
    cout << "insert failed" << endl;
  }
  cout << endl;
  //4.m[key_value] = mapped_value 
  //這種元素安插方式比一般的map安插方式來得慢,原因是新元素必須先使用 default構造函數將實值初始化,而這個初值馬上又被真正的value給覆蓋了。
  m[3] = "222";
  m[0] = "000";
  m[-1] = "-1-1-1";
  m[-100] = "-100";
  printMap(m.begin(),m.end());
  mapType::mapped_type mappedValue = m[1];
  cout << mappedValue << endl;
  mapType::iterator it = m.begin();
  advance(it,2);
  it = m.insert(it,mapType::value_type(22,"22"));
  //cout << it->first << '\t' << it->second << endl;
  printMap(m.begin(),m.end());
  //[first,last)mapType m2;char buffer[5] = {0};
  for (mapType::size_type i = 0;i != 10; ++i)
  {
    sprintf(buffer,"%d",i*100+5);
    m2.insert(mapType::value_type(i,buffer));
  }
  cout << endl;
  printMap(m2.begin(),m2.end());
  mapType::iterator beg = m.begin();
  mapType::iterator end = beg;
  //advance(end,3);
  //m2.insert(beg,end);
  //cout << endl;
  //printMap(m2.begin(),m2.end());
  m2.insert(beg,m.find(1));
  //[beg,key_value==1)
  cout << endl;
  printMap(m2.begin(),m2.end());
  char ch;
  cin >> ch;
  return EXIT_SUCCESS;
}

void printMap(mapType::iterator begin,mapType::iterator end)

{
  for(mapType::iterator iter = begin; iter != end; iter++)
  cout << iter->first << " = "<< (*iter).second << endl;
  cout << endl;
}

//erase

1.void erase ( iterator position );

2.size_type erase ( const key_type& x );//the function returns the number of elements erased

3.void erase ( iterator first, iterator last );

eg:
  map<char,int> mymap;
  map<char,int>::iterator it;
  // insert some values:
  mymap['a']=10;
  mymap['b']=20;
  mymap['c']=30;
  mymap['d']=40;
  mymap['e']=50;
  mymap['f']=60;
  it=mymap.find('b');
  mymap.erase (it);                   // erasing by iterator
  mymap.erase ('c');                  // erasing by key, like list.remove(value), but list return void
  it=mymap.find ('e');
  mymap.erase ( it, mymap.end() );    // erasing by range
Observers:

key_comp Return key comparison object
value_comp Return value comparison object
Operations:

find Get iterator to element
count Count elements with a specific key
lower_bound Return iterator to lower bound
upper_bound Return iterator to upper bound
equal_range Get range of equal elements

//find

1.iterator find ( const key_type& x );
2.const_iterator find ( const key_type& x ) const;

//An iterator to the element, if the specified key value is found, or map::end if the specified key is not found in the container.
//count
//1 if an element with a key equivalent to x is found, or zero otherwise.
lower_bound>=[包括他在內的他的iterator]
1.iterator lower_bound ( const key_type& x );
2.const_iterator lower_bound ( const key_type& x ) const;

eg:
  map<char,int> mymap;
  map<char,int>::iterator it,itlow,itup;
  mymap['a']=20;
  mymap['b']=40;
  mymap['c']=60;
  mymap['d']=80;
  mymap['e']=100;
  itlow=mymap.lower_bound ('b');  // itlow points to b
  itlow->second();//20
  itup=mymap.upper_bound ('d');   // itup points to e (not d!)
  (*itup)->second();//100
  mymap.erase(itlow,itup);        // erases [itlow,itup)
  // print content:
  for ( it=mymap.begin() ; it != mymap.end(); it++ )
    cout << (*it).first << " => " << (*it).second << endl;
upper_bound>[比他大的下一個iterator]
1.iterator upper_bound ( const key_type& x );
2.const_iterator upper_bound ( const key_type& x ) const;

equal_range
1.pair<iterator,iterator>
    equal_range ( const key_type& x );
2.pair<const_iterator,const_iterator>
    equal_range ( const key_type& x ) const;

//return a pair<iterator,iterator>
返回一個pair[p.]分別指向lower_bound和upper_bound
eg:
  map<char,int> mymap;
  pair<map<char,int>::iterator,map<char,int>::iterator> ret;
  mymap['a']=10;
  mymap['b']=20;
  mymap['c']=30;
  ret = mymap.equal_range('b');
  cout << "lower bound points to: ";
  cout << ret.first->first << " => " << ret.first->second << endl;
  cout << "upper bound points to: ";
  cout << ret.second->first << " => " << ret.second->second << endl;
  //如果不存在,就指向大於所指的x值的iterator,除此之外就指向了c.end()
	map<char,int> mymap;
	map<char,int>::iterator it;
	typedef map<char,int>::iterator itType;
	mymap['a']=20;
	mymap['b']=40;
	mymap['c']=60;
	//mymap['d']=80;
	mymap['e']=100;
	mymap['f']=120;
	mymap['g']=140;
	pair<itType,itType> p = mymap.equal_range('d');//如果這裏是一個'g',下面就出錯了,沒有解引用了
	cout << p.first->first << '\t' << p.first->second << endl;	//e = 100
	cout << p.second->first << '\t' << p.second->second << endl;//e = 100
Allocator:

get_allocator Get allocator
eg:
  int psize;
  map<char,int> mymap;
  pair<const char,int>* p;
  // allocate an array of 5 elements using mymap's allocator:
  p=mymap.get_allocator().allocate(5);	//分配了5個
  // assign some values to array
  psize = (int) sizeof(map<char,int>::value_type)*5;
  cout << "The allocated array has a size of " << psize << " bytes.\n";
  mymap.get_allocator().deallocate(p,5);
//移除迭代器所指元素的正確做法  
typedef std::map<std::string,float> StringFloatMap;  
StringFloatMap coll;  
StringFloatMap::iterator pos;  
for(pos = coll.begin(); pos != coll.end(); )  
{  
if(pos->second == value)  
    coll.erase(pos++);  
else
  
    ++pos;  
} 
發佈了39 篇原創文章 · 獲贊 0 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章