STL—map之總結

一.map的原型
1.map
template <class _Key, class _Tp, class _Compare, class _Alloc>
class map {...}


2.multimap
template <class _Key, class _Tp, class _Compare, class _Alloc>
class multimap {...}


由此可以看出我們可以根據需要自定義compare Function


二.自定義compare Function
2.1重載<操作運算符


2.1.1以成員函數方式去重載
inline bool operator<(const myClass &_myclass) const {
	if(id != _myclass.id)
		return id < _myclass.id;
	else
		return name < _myclass.name;
}

2.2.2以友元函數方式去重載
bool operator<(const myClass &m1, const myClass &m2){
	if(m1.getID() != m2.getID())
		return m1.getID() < m2.getID();
	else
		return m1.getString() < m2.getString();
}

2.2.3以函數對象的方式去定義
struct myCompare{
	bool operator()(const myClass &m1, const myClass &m2){
		if(m1.getID() != m2.getID())
			return m1.getID() < m2.getID();
		else
			return m1.getString() < m2.getString();	
	}
};

注意點:在自定義比較函數時,不能丟失const


三.例子

代碼如下;

#include <iostream>
#include <map>
//#include <unordered_map>
#include <string>
#include <algorithm>
using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::sort;
using std::map;
//using std::unordered_map;
using std::string;

const int N = 1003;

class myClass{
private:
	string name;
	int id;
public:
	string getString() const { return name; }
	int getID() const {return id; }
	myClass(string _name, int _id):name(_name), id(_id) {}
	//重載<操作運算符的時候不能丟掉const
	/*inline bool operator<(const myClass &_myclass) const {
		if(id != _myclass.id)
			return id < _myclass.id;
		else
			return name < _myclass.name;
	}*/
	inline friend bool operator<(const myClass &m1, const myClass &m2);
};

//重載<操作運算符的時候不能丟掉const
bool operator<(const myClass &m1, const myClass &m2){
	if(m1.getID() != m2.getID())
		return m1.getID() < m2.getID();
	else
		return m1.getString() < m2.getString();
}

struct myCompare{
	bool operator()(const myClass &m1, const myClass &m2){
		if(m1.getID() != m2.getID())
			return m1.getID() < m2.getID();
		else
			return m1.getString() < m2.getString();	
	}
};

int main(){
	freopen("./output.txt", "w", stdout);
	map<myClass, int, myCompare> cMap;
	for(int i = 0; i < N; i++){
		string tName = "cjw";
		char ss[10];
		string tmp;
		sprintf(ss, "%d", i);
		tmp = ss;
		tName = tName + tmp;
		myClass tClass(tName, i);
		cMap[tClass] = i * 2;
	}
	for(map<myClass, int, myCompare>::iterator ite = cMap.begin(); ite != cMap.end(); ite++){
		cout << ite->first.getString() << " " << ite->first.getID() << " " << ite->second << endl;
	}
}


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