STL map使用自定义对象做key

#include 
using namespace std;

struct grid
{
	unsigned short x;
	unsigned short y;
	bool operator<(const grid& g)const
	{
		if ( y < g.y)
		{
			return true;
		}
                else if(y==g.y && x < g.x)
		{
			return true;
		}
		return false;
	}
};

int _tmain(int argc, _TCHAR* argv[])
{
	map lev;
	grid g;

	g.x = 0;
	g.y = 0;
	lev[g] = 1;

	g.x = 0;
	g.y = 1;
	lev[g] = 2;

	g.x = 1;
	g.y = 0;
	lev[g] = 3;

	g.x = 1;
	g.y = 1;
	lev[g] = 4;

	grid gg;
	gg.x = 1;
	gg.y = 0;

	int nn = lev[gg];
	return 0;
}

STL中map,当使用自定义对象做key时,需要重载<操作符,示例


你可能感兴趣的:(C/C++)