大O表示法来表示算法的速度
LinearMap.h线性映射
#pragma once
#include <vector>
using namespace std;
template<class Key, class Value>
class LinearMap //线性映射----做对比用,无实际意义
{
public:
LinearMap(int size = 101) : array(size)
{
curSize = 0;
}
void Put(const Key &k, const Value &v)
{
array[curSize] = DataEntry(k, v);
++curSize;
}
Value Get(const Key &k)
{
for(int i = 0; i < curSize; i++)
{
if(array[i].key == k) //线性查找
return array[i].value;
}
return Value();
}
private:
struct DataEntry
{
Key key;
Value value;
DataEntry(const Key &k = Key(), const Value &v = Value()):key(k), value(v){}
};
vector<DataEntry> array;
int curSize;
};
HaspMap.h
#include <iostream>
#include <vector>
using namespace std;
template<class Key, class Value>
class HashMap //哈希映射 -- 速度很快
{
public:
HashMap(int size = 101) : array(size)
{
curSize = 0;
}
void Put(const Key &k, const Value &v)
{
int pos = MyHash(k);
array[pos] = DataEntry(k, v);
++curSize;
}
Value Get(const Key &k)
{
int pos = MyHash(k);
if(array[pos].key == k)
return array[pos].value;
else
return Value();
}
//哈希函数(字符串) BKDR哈希算法
unsigned hash(const Key &k) const
{
unsigned int hashVal = 0;
int seed = 31; //也可以是131 1313 13131 131313
//const char *keyp = reinterpret_cast<const char*>(&k);
for(int i = 0; i < k.size(); i++)
hashVal = seed * hashVal + k[i];
//cout << sizeof(keyp) << endl;
return hashVal;
}
int MyHash(const Key &k) const
{
unsigned hashVal = hash(k);
hashVal %= array.size();
return hashVal;
}
private:
struct DataEntry
{
Key key;
Value value;
DataEntry(const Key &k = Key(), const Value &v = Value()):key(k), value(v){}
};
vector<DataEntry> array;
int curSize;
};
main.h
#include <iostream>
#include <map> //映射(也叫字典) 二叉树映射, 不是哈希映射
#include <string>
#include "LinearMap.h" //线性映射
#include "HaspMap.h"
using namespace std;
int main()
{
/**********二叉树(红黑树)映射,速度很快**********/
cout << "**************二叉树(红黑树)映射,速度很快***************" << endl;
map<string, int> m;
m["yang"] = 99;
m["zhang"] = 45;
m["li"] = 75;
//....继续保存,保存了100万个
cout << m["yang"] << endl;
/*************数组的优点***********/
cout << "**************数组的优点,存取速度很快***************" << endl;
int arr[100000] ;
for(int i = 0; i < 100000; i++)
arr[i] = i % 100;
cout << arr[8] << endl;
cout << arr[65] << endl;
cout << arr[98766] << endl;
/**************仅供学习的线性映射*********************/
cout << "**************仅供学习的线性映射,做对比用***************" << endl;
LinearMap<string, int> lm;
lm.Put("yang", 99);
lm.Put("zhang", 88);
//.......继续放很多数据
cout << "LinearMap: " << lm.Get("yang") << endl;
/****************自己做的哈希映射***************/
cout << "**************自己做的哈希映射***************" << endl;
HashMap<string, int> hm;
cout << "哈希值:" << hm.hash("Bill") << endl;
cout << "哈希值:" << hm.MyHash("Bill") << endl;
hm.Put("Bill", 999);
hm.Put("Tom", 888);
hm.Put("Mary", 777);
cout << "HashMap:" << hm.Get("Tom") << endl;
cout << int() << endl;
return 0;
}