结构体数组做映射(写了个风格还算靠谱的程序, 欢迎大家找茬拍砖, 共同进步)

      之前说过了, 数组的本质就是i到a[i]的映射, 下面, 我们看看更高级的映射---利用结构体数组。  心血来潮, 突然想写个代码风格比较好的程序, 欢迎大家找茬拍砖, 共同进步:

 

#include <iostream>
#define  COLOR_STR_LEN  100  // 颜色字符串的最大长度
using namespace std;

// 基本数据类型
typedef char SYS_INT8;
typedef int  SYS_INT32;

// 函数返回值状态
enum
{
	SYS_0K = 0,
	SYS_ERROR = -1,
};

// 基本颜色种类
typedef enum
{
	UNDEF = -1, // 未定义
	RED = 0,
	GREEN = 1,
	BLACK = 2,
	YELLOW = 10,
	WHITE = 15,
}Color;

// 从枚举到字符串的映射
typedef struct
{
	Color col;
	SYS_INT8 szColor[COLOR_STR_LEN + 1];
}ColorMap;

// 颜色映射的数组
ColorMap colMap[] = 
{
	{RED, "red"},
	{GREEN, "green"},
	{BLACK, "black"},
	{YELLOW, "yellow"},
	{WHITE,  "white"},
};


// 函数功能:根据颜色字符串, 查找对应的颜色值
SYS_INT32 getValueFromColorStr(Color *pcol, const SYS_INT8* pColor)
{
	if(NULL == pcol && NULL == pColor)
	{
		printf("NULL pointer");
		return SYS_ERROR;
	}

	SYS_INT32 size = sizeof(colMap) / sizeof(colMap[0]);
	SYS_INT32 i = 0;
	for(i = 0; i < size; i++)
	{
		if(0 == strcmp(pColor, colMap[i].szColor))
		{
			*pcol = colMap[i].col;
			return SYS_0K;
		}
	}

	printf("no match for %s\n", pColor);
	return SYS_ERROR;
}

// 根据颜色值, 查找对应的颜色字符串
SYS_INT32 getStrFromColorValue(Color col, SYS_INT8* pBuf, SYS_INT32 bufSize)
{
	if(NULL == pBuf)
	{
		printf("NULL pointer");
		return SYS_ERROR;
	}

	if(bufSize <= 0)
	{
		printf("bufSize(%d) is invalid", bufSize);
		return SYS_ERROR;
	}

	SYS_INT32 size = sizeof(colMap) / sizeof(colMap[0]);
	SYS_INT32 i = 0;
	for(i = 0; i < size; i++) 
	{
		if(col == colMap[i].col)
		{
			strncpy(pBuf, colMap[i].szColor, bufSize - 1);
			pBuf[bufSize - 1] = '\0';
			return SYS_0K;
		}
	}

	printf("no match for %d", (SYS_INT32)col);
	return SYS_ERROR;
}


SYS_INT32 main()
{
	// 根据颜色字符串, 查找对应的颜色值
	SYS_INT32 iRet = SYS_ERROR;
	Color col = UNDEF;
	const SYS_INT8* pTest = "yellow";
	iRet = getValueFromColorStr(&col, pTest);
	if(SYS_0K != iRet)
	{
		printf("cannot find %s\n", pTest);
		return SYS_ERROR;
	}

	cout << col << endl;


	// 根据颜色值, 查找对应的颜色字符串
	SYS_INT8 szColor[COLOR_STR_LEN + 1] = {0};
	Color colTest = GREEN;
	iRet = getStrFromColorValue(colTest, szColor, sizeof(szColor));
	if(SYS_0K != iRet)
	{
		printf("cannot find %d", (SYS_INT32)colTest);
		return SYS_ERROR;
	}
	
	cout << szColor << endl;


	return SYS_0K;
}

 

      欢迎大家七嘴八舌害羞害羞害羞

 

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值