非红黑树,排序+二分搜索,查找修改O(logN),插入删除O(N)
#ifndef MAP_H #define MAP_H #include "main.h" /*----------Custom----------*/ typedef struct{ short* Addr; short MaxValue; short MinValue; uchar ReadOnly; } MODBUS_DataType; #define MAP_TypeKey ushort #define MAP_TypeValue MODBUS_DataType /*----------End----------*/ typedef struct{ MAP_TypeKey Key; MAP_TypeValue Value; } MAP_Element; #define MAP_MaxSize 20 typedef struct{ MAP_Element Element[MAP_MaxSize]; int Size; } MAP_TypeDef; #ifdef MAP_C #include "stdlib.h" void MAP_Swap(MAP_Element* a, MAP_Element* b); /*----------Custom----------*/ int MAP_Compare(const void* a, const void* b) { return (*(MAP_Element*)a).Key - (*(MAP_Element*)b).Key; } /*----------End----------*/ #endif int MAP_Find (MAP_TypeDef* mp, MAP_TypeKey key ); void MAP_Insert(MAP_TypeDef* mp, MAP_TypeKey key, MAP_TypeValue value); void MAP_Erase (MAP_TypeDef* mp, MAP_TypeKey key ); char MAP_Get (MAP_TypeDef* mp, MAP_TypeKey key, MAP_TypeValue* out ); char MAP_Set (MAP_TypeDef* mp, MAP_TypeKey key, MAP_TypeValue value); #endif
#define MAP_C #include "map.h" int MAP_Find(MAP_TypeDef* mp, MAP_TypeKey key) { int l = 0; int r = mp->Size; MAP_Element tmp; tmp.Key = key; while(l <= r) { ushort mid = (l + r) >> 1; int ans = MAP_Compare(&mp->Element[mid], &tmp); if(ans > 0) { r = mid - 1; } else if(ans < 0) { l = mid + 1; } else { return mid; } } return -1; } void MAP_Swap(MAP_Element* a, MAP_Element* b) { MAP_Element tp; tp = *a; *a = *b; *b = tp; } void MAP_Insert(MAP_TypeDef* mp, MAP_TypeKey key, MAP_TypeValue value) { MAP_Element tmp; tmp.Key = key; tmp.Value = value; if(mp->Size == 0) { mp->Element[0] = tmp; mp->Size ++; return; } int pos; for(pos = 0; pos < mp->Size; pos ++) { int ans = MAP_Compare(&mp->Element[pos], &tmp); if(ans == 0) { mp->Element[pos] = tmp; return; } else if(ans > 0) { break; } } for(int i = mp->Size; i > pos; i --) { mp->Element[i] = mp->Element[i - 1]; } mp->Element[pos] = tmp; mp->Size ++; } void MAP_Erase(MAP_TypeDef* mp, MAP_TypeKey key) { MAP_Element tmp; tmp.Key = key; int pos; for(pos = 0; pos < mp->Size; pos ++) { int ans = MAP_Compare(&mp->Element[pos], &tmp); if(ans == 0) { break; } else if(ans > 0) { return; } } mp->Size --; for(int i = pos; i < mp->Size; i ++) { mp->Element[i] = mp->Element[i + 1]; } } char MAP_Get(MAP_TypeDef* mp, MAP_TypeKey key, MAP_TypeValue* out) { MAP_Element tmp; tmp.Key = key; int pos = MAP_Find(mp, tmp.Key); if(pos == -1) { return 1; } *out = mp->Element[pos].Value; return 0; } char MAP_Set(MAP_TypeDef* mp, MAP_TypeKey key, MAP_TypeValue value) { MAP_Element tmp; tmp.Key = key; tmp.Value = value; int pos = MAP_Find(mp, tmp.Key); if(pos == -1) { return 1; } mp->Element[pos] = tmp; return 0; }
标签:tmp,Map,MAP,int,pos,Element,简易,mp,模板 From: https://www.cnblogs.com/PolarBearINBrown/p/17153188.html