1. 程式人生 > >c++ STL 之 map及multimap

c++ STL 之 map及multimap


 

#define VNAME(value) {cout<<(#value)<<":"<<endl;}

template<class T>
void print_map(T &v)
{
	for (auto tmp : v)
	{
		cout<<"key:"<<tmp.first<<" value:"<<tmp.second<<endl;
	}
}


/**
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與set的區別就是:set是map的特例,即key和value相同
 **故set的成員函式和map類似
 **multimap與map的區別為:multimap有序,可以存相同key的value_type
 **/

void test_map(){
	map<int,string> a;
	a[1] = "test";
	a[2] = "big";
	a[3] = "small";
	a[4] = "middle";

	map<int,string,classcomp> c;
	c[5] = "five";
	c[6] = "six";		//可以通過key賦值,也可以通過key訪問value
	c[7] = "seven";

	/**
	 迭代器:begin,end,rbegin,rend及對應的const
	 map的迭代器不能與整數進行加操作,因為記憶體不是連續的,底層實現紅黑樹
	 **/

	cout<<"size of a :" <<a.size()<<endl;
	cout<<"max_size of a :"<<a.max_size()<<endl;
	cout<<"key:2 -- value:"<<a[2]<<endl;
	//cout<"key:3 -- value:"<<a.at(3)<<endl;			//c++11有些編譯器沒有完全支援

	//返回pair<iterator,bool>
	a.insert(c.begin(),c.find(6));	//1,2,3,4,5
	a.insert(map<int,string>::value_type(8,"eight"));
	a.insert(a.find(3),pair<int,string>(9,"nine"));		//因為有序,所以插入位置不怎麼管用
	a.emplace(10,"ten");
	a.emplace_hint(a.end(),11,"eleven");

	VNAME(a)
	print_map(a);

	a.erase(a.find(2),a.find(4));		//返回被刪除元素的下一個存在元素的迭代器
	a.erase(1);		//因為有序唯一,所以返回size_t為0或者1
	a.erase(a.begin());
	VNAME(a)
	print_map(a);

	//a.swap(c);		//交換內容,這裡錯誤,a和c不是相同型別
	//key_comp();		//獲取key比較函式,即模板第三個引數
	// value_comp();	//返回一個value比較函式,區別於key比較函式

	cout<<"key num of 2 in a is "<<a.count(2)<<endl;

	//multimap中使用獲取一個範圍
	auto i = a.lower_bound(3);		//若key不存在返回第一個元素迭代器
	auto j = a.upper_bound(8);		//存在返回下一個元素的迭代器;不存在,返回第二個元素的迭代器
	auto k = a.equal_range(3);		

	c.clear();		//清空c中資料
	if (c.empty())
	{
		cout<<"c is empty"<<endl;
	}

	//multimap ,相對於map來說,可以儲存多個相同key相同的值

	cout<<endl<<endl;
}