本文主要验证:C++模板、模板类、内存比较关键字
MapIndex.h文件:
#ifndef TEMPLATE_CLASS_H
#define TEMPLATE_CLASS_H
template <class Key, class Value>
class MapIndex{
private:
Key* keys;
Value* values;
int size = 0;
int inuse = -1;
~MapIndex();
public:
MapIndex(int);
bool add(Key, Value);
Value* get(Key);
};
#endif
test.cpp文件:
#include<iostream>
#include"MapIndex.h"
using namespace std;
template<class T_SW>
void do_sw(T_SW & a, T_SW & b){
T_SW c = a + b;
a = c - a;
b = c - a;
}
void do_sw(char & a, char & b){
cout << "显式具体化" << endl;
}
template <class Key, class Value>
MapIndex<Key, Value>::MapIndex(int _size){
this->keys = (Key*)malloc(sizeof(Key)*_size);
this->values = (Value*)malloc(sizeof(Value)*_size);
this->size = _size;
}
template <class Key, class Value>
MapIndex<Key, Value>::~MapIndex(){
free(this->keys);
free(this->values);
this->size = 0;
}
template <class Key, class Value>
bool MapIndex<Key, Value>::add(Key _key, Value _value){
if ((this->inuse + 1) >= this->size){
this->inuse = this->size - 1;
return false;
}
++(this->inuse);
this->keys[this->inuse] = _key;
this->values[this->inuse] = _value;
return true;
}
template <class Key, class Value>
Value* MapIndex<Key, Value>::get(Key _key){
for (int i = 0; i <= this->inuse; i++){
if (memcmp(&(this->keys[i]), &_key, sizeof(Key)) == 0){
return &this->values[i];
}
}
return NULL;
}
int main(int argc, char *argv[])
{
int i_a = 1;
int i_b = 2;
cout << "i_a is " << i_a << " i_b is " << i_b << endl;
do_sw(i_a, i_b);
cout << "i_a is " << i_a << " i_b is " << i_b << endl;
//------------------------------------------------------
double d_a = 1.1;
double d_b = 2.2;
cout << "d_a is " << d_a << " d_b is " << d_b << endl;
do_sw(d_a, d_b);
cout << "d_a is " << d_a << " d_b is " << d_b << endl;
//------------------------------------------------------
char c_a = 'a';
char c_b = 'b';
cout << "c_a is " << c_a << " c_b is " << c_b << endl;
do_sw(c_a, c_b);
cout << "c_a is " << c_a << " c_b is " << c_b << endl;
//------------------------------------------------------
int* a = new int(5);
a[2] = 5;
int* b = &a[2];
cout << *b << endl;
cout << memcmp(a, b, sizeof(int)) << endl;
//------------------------------------------------------
MapIndex<char, int>* list = new MapIndex<char, int>(2);
list->add('y', 1);
list->add('g', 2);
cout << *list->get('g') << endl;
//------------------------------------------------------
char end;
cin >> end;
}
运行结果: