STL—map之总结

  • Post author:
  • Post category:其他


一.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;
	}
}



版权声明:本文为newner原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。