c++ stl 一些东西

std::map: 其key是基于比较运算符的,因此自定义类型需要为该类型设定比较运算符操作

class A {
public:
        bool operator < (const A & b) {
                return mm < b.mm;
        }
 private:
        int mm;
 }
 std::map<A,int> kk;

std::unordered_map:基于hash实现,需要为自定义类型设定==运算符和哈希函数

class A{
public:
        bool operator == (const A & p) const {
                return mm == p.mm;
        }
        int get_value() const {
                return mm;
        }
private:
        int mm;
};
struct Hash {
        size_t operator () (const A & mm) const{
                return hash<int>()(mm.get_value());
        }
};

int main(){
        unordered_map<A, int, Hash> ids;
        A s;
        ids[s] = 1;
}

unordered_map也可以通过模板特化的形式

#include <iostream>
#include <unordered_map>
using namespace std;
class A{
public:
	bool operator == (const A & p) const {
		return mm == p.mm;
	}
	int get_value() const {
		return mm;
	}
private:
	int mm;
};
struct Hash {
	size_t operator () (const A & mm) const{
		return hash<int>()(mm.get_value());
	}
};
namespace std {
template<>
class hash<A>{
public:
	size_t operator () (const A & mm) const{
		return hash<int>()(mm.get_value());
	}
};
}
int main(){
	unordered_map<A, int> ids;
	A s;
	ids[s] = 1;
}

猜你喜欢

转载自blog.csdn.net/jxhaha/article/details/101172903