之前说过了, 数组的本质就是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;
}
欢迎大家七嘴八舌