101Triplet

三元组的实现 包含4个文件:

    c1.h 是预处理指令;

    c1-1.h 是Triplet的数据结构;

    bo1-1.cpp 是Triplet的基本操作函数(basic operations 缩写为 bo);

    main1-1.cpp 是测试函数。

//c1.h
#include<iostream>
#include<process.h>
#include<malloc.h>
#include<string>

#define OK 1
#define ERROR 0
#define INFEASIBLE -1

typedef int Status;
//c1-1.h
typedef ElemType *Triplet;
//bo1-1.cpp
#ifndef bo1_1
#define bo1_1

#include "c1.h"
using namespace std;

Status InitTriplet(Triplet &T, ElemType v1, ElemType v2, ElemType v3)
{
	if (!(T = (ElemType *)malloc(3 * sizeof(ElemType))))
		exit(OVERFLOW);
	T[0] = v1, T[1] = v2, T[2] = v3;
	return OK;
}

void Show(Triplet T)
{
	cout << "Show: " << T[0] << " " << T[1] << " " << T[2] << endl;
}

Status DestroyTriplet(Triplet &T)
{
	free(T);
	T = NULL;
	return OK;
}

ElemType Get(Triplet T, int index)
{
	if (index >= 1 && index <= 3)
		return T[index - 1];
	else
		cout << "wrong index!";
}

Status Put(Triplet &T, int index, ElemType e)
{
	if (index >= 1 && index <= 3)
	{
		T[index - 1] = e;
		return OK;
	}
	else
		return ERROR;
}

bool IsAscending(Triplet T)
{
	return T[0] <= T[1] && T[1] <= T[2];
}

bool IsDescending(Triplet T)
{
	return T[0] >= T[1] && T[1] >= T[2];
}

ElemType Max(Triplet T)
{
	return T[0] >= T[1] ? T[0] >= T[2] ? T[0] : T[2] : T[1] >= T[2] ? T[1] : T[2];
}

ElemType Min(Triplet T)
{
	return T[0] <= T[1] ? T[0] <= T[2] ? T[0] : T[2] : T[1] <= T[2] ? T[1] : T[2];
}

#endif
//main1-1.cpp
#include "c1.h"
typedef int ElemType;
#include "c1-1.h"
#include "bo1-1.cpp"
using namespace std;
int main()
{
	Triplet T = NULL;
	cout << "InitTriplet: " << InitTriplet(T, 1, 2, 3) << endl;
	Show(T);

	ElemType e;
	e = Get(T, 1);
	cout << "Get: " << e << endl;

	cout << "IsAscending: " << IsAscending(T) << endl;
	cout << "IsDescending: " << IsDescending(T) << endl;

	Put(T, 2, 22);
	Show(T);

	cout << "Max: " << Max(T) << endl;
	cout << "Min: " << Min(T) << endl;

	cout << "DestroyTriplet: " << DestroyTriplet(T) << endl;
	cin.get();
	return 0;
}


你可能感兴趣的:(数据结构,实现,C语言)