C++复习——template,template类,memcmp

本文主要验证: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;
}
运行结果:



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值