STL map的基本用法

map容器

  • **<鍵,值>**對
    在這裏插入圖片描述

  • 鍵值不允許重複。

  • 如果map中沒有鍵值,而直接插入,則操作是允許的;另外如果直接使用“++”運算符,則從0開始直接計數。並把這個<鍵,值>對插入到map中。

常用函數和操作
1.map的創建、插入和遍歷

#include<map>
#include<iostream>
#include<string>
using namespace std;

int main()
{
	map<string, float> a;
	a["hehe"] = 12.5;
	a["xixi"] = 89.6;
	map<string, float>::iterator it;
	for(it = a.begin(); it != a.end(); it++)
		cout<<(*it).first<<' '<<(*it).second<<endl;
	a["hehe"] = 45.2;
	cout<<"修改後的hehe的值:"<<a["hehe"]<<endl;	
}

上面的代碼的運行截圖

(*it).first     表示鍵,注意鍵不可以用這種方法修改,如:
(*it).first = "eee",是錯誤的操作。
(*it).second    表示對應的值

2.查找鍵和刪除鍵
可以使用clear()清空map

map<int, int> a;
a.clear();

也可以使用erase()刪除。括號中可以直接寫相應的鍵值,也可以寫iterator的位置。

a.erase("hehe");//直接使用鍵,刪除“hehe”;
a.erase(++a.begin());//刪除“xixi”

使用**find()**函數可以搜索某個鍵。搜索到了的話返回迭代器的位置,搜索不到返回end()位置。

#include<map>
#include<iostream>
#include<string>
using namespace std;

int main()
{
	map<string, float> a;
	a["hehe"] = 12.5;
	a["xixi"] = 89.6;
	map<string, float>::iterator it;
	it = a.find("xixi");
	a.erase(it); 
	for(it = a.begin(); it != a.end(); it++)
		cout<<(*it).first<<' '<<(*it).second<<endl;
}

另外,把元素插入到map中時,自動按照鍵值從小到大排序。可以自己設置比較函數,比較函數的寫法類似於sort()中的寫法。

//未使用自定義比較函數時
#include<iostream>
#include<map>
using namespace std;
bool comp(int a, int b){
}
int main()
{
	map<int, char> a;
	a[10] = 'a';
	a[5] = 'b';
	a[25] = 'c';
	a[15] = 'd';
	map<int, char>::iterator it;
	for(it = a.begin(); it != a.end(); it++)
		cout<<(*it).first<<' '<<(*it).second<<endl;
}

在這裏插入圖片描述

#include<iostream>
#include<map>
using namespace std;
struct mycomp
{
	bool operator() (const int &a, const int &b)
		return a > b;
};
int main()
{
	map<int, char, mycomp> a;
	a[10] = 'a';
	a[5] = 'b';
	a[25] = 'c';
	a[15] = 'd';
	map<int, char, mycomp>::iterator it;
	for(it = a.begin(); it != a.end(); it++)
		cout<<(*it).first<<' '<<(*it).second<<endl;
}

對於結構體,需要重載。。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章