CMapのサンプル

FEMで使う場合、ユーザー定義クラスとハッシュを組み合わせる必要がある。友人からサンプルをもらったので、メモしておく。
私は、FemNode2が気に入ったので、そちらを流用することにする。

#pragma once
#include "stdafx.h"

class FemNode
{
public:
	int id;
	float xyz[3];

	// コピー用
	FemNode& operator=(const FemNode& in){
		id = in.id;
		memcpy(xyz,in.xyz,sizeof(xyz));
		return *this;
	}
};

// HashKey() HashKey生成用関数
template<> UINT AFXAPI HashKey(FemNode& key)
{
	return reinterpret_cast<UINT>(&key);
};

// CompareElements() 比較用関数
template<> BOOL AFXAPI CompareElements( const FemNode* pElement1, const FemNode* pElement2 )
{
	if(pElement1->id && pElement2->id)
	{
		return(TRUE);
	}
	return(FALSE);
};

class FemNode2
{
public:
	int id;
	float xyz[3];

	// 比較用operator
	BOOL operator==(const FemNode2& in) const {
		if(id == in.id && memcmp(xyz,in.xyz,sizeof(xyz)) == 0) return TRUE;
		return FALSE;
	}

	// HashKey()用に適当なDWORD値を返すoperator
	operator DWORD() const throw(){
		return reinterpret_cast<DWORD>(this);
	}

	// コピー
	FemNode2& operator=(const FemNode2& in) {
		id = in.id;
		memcpy(xyz,in.xyz,sizeof(xyz));
		return *this;
	}

};

class CMapTest
{
public:

	CMapTest(void)
	{
	}

	~CMapTest(void)
	{
	}

	void Test(){
		// HashKey(),CompareElements()を自作する方法
		clock_t t1 = clock();
		CMap<FemNode*,FemNode*&,int,int> map1;
		CMap<int,int,FemNode*,FemNode*&> map11;
		map1.InitHashTable(1000000);
		map11.InitHashTable(1000000);
		FemNode* fn1;
		for (int i = 0; i < 1000000;i ++) {
			fn1 = new FemNode;
			fn1->id = i+1;
			fn1->xyz[0] = i;
			fn1->xyz[1] = i+1;
			fn1->xyz[2] = i+2;
			map1[fn1] = i+1;
			int retVal1 = map1[fn1];
			map11[fn1->id] = fn1;
			FemNode* retVal11 = map11[fn1->id];
		}
		printf("FemNode %.2f sec elapsed.\n",(double)(clock()-t1)/CLOCKS_PER_SEC);

		// operatorで済ませちゃう方法
		t1 = clock();
		CMap<FemNode2*,FemNode2*&,int,int> map2;
		CMap<int,int,FemNode2*,FemNode2*&> map22;
		map2.InitHashTable(1000000);
		map22.InitHashTable(1000000);
		FemNode2* fn2;
		for (int i = 0; i < 1000000; i++) {
			fn2 = new FemNode2;
			fn2->id = i+1;
			fn2->xyz[0] = i;
			fn2->xyz[1] = i+1;
			fn2->xyz[2] = i+2;
			map2[fn2] = i+1;
			int retVal2 = map2[fn2];
			map22[fn2->id] = fn2;
			FemNode2* retVal22 = map22[fn2->id];
		}
		printf("FemNode2 %.2f sec elapsed.\n",(double)(clock()-t1)/CLOCKS_PER_SEC);
	}
};
実行結果:
FemNode 1.67 sec elapsed.
FemNode2 1.64 sec elapsed.