# 算法导论第11章散列表11.1直接寻址表

```/*
*
*  Created on: Feb 11, 2015
*      Author: sunyj
*/
#include <stdint.h>
#include <iostream>
#include <string.h>
// return T[k]

// T[x.key] = x

// T[x.kdy] = NIL

template <class Type> class ElemType {
public:
ElemType() : key(0), data('\0') { }
ElemType(int64_t const k, Type const d) : key(k), data(d) { }

int64_t key; // key belongs to a small range like [0, 1, 2, 7, 99.... ]
Type data;
};

template <class Type> class DirectAddressTable {
public:
{
data = new ElemType<Type>[n];
memset(data, -1, n * sizeof(ElemType<char>));
}
~DirectAddressTable() { delete [] data; }
ElemType<Type> search(int64_t const key)
{
if (-1 == data[key].key)
{
}
return data[key];
}
void insert(ElemType<Type> x)
{
if (-1 != data[x.key].key)
{
std::cout << "x.key already exist, insert failed" << std::endl;
return ;
}
data[x.key] = x;
}
void del(ElemType<Type> x)
{
if (-1 == data[x.key].key)
{
std::cout << "x.key not exist, delete failed" << std::endl;
return ;
}
data[x.key].key = -1;
}
private:
ElemType<Type>* data;
int64_t size;
};

int main()
{
ElemType<char> a(2, 'b');
ElemType<char> q(3, '8');
ElemType<char> c(22, 'q');
ElemType<char> w(9, 'N');

// Assume there are at most 100 ElemType element,

table.insert(a);
table.insert(q);
table.insert(c);
ElemType<char> tmp;
tmp.key = 3;
tmp = table.search(tmp.key);
std::cout << tmp.data << std::endl;
tmp.key = 4;
tmp = table.search(tmp.key);
std::cout << tmp.data << std::endl;

table.insert(a); // insert failed
table.del(a);
table.insert(a); // ok
tmp = table.search(2);
std::cout << tmp.data << std::endl;
return 0;
}
```

原文作者：孙永杰
原文地址: https://www.cnblogs.com/sunyongjie1984/p/4286900.html
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。