我正在将一些c ++代码移植到c.什么是c中std :: map的可行等价物?我知道c中没有等价物.
这就是我想要使用的:
在c ++中:
std::map< uint, sTexture > m_Textures;
Run Code Online (Sandbox Code Playgroud)
在c:
typedef struct
{
uint* intKey;
sTexture* textureValue;
} sTMTextureMap;
Run Code Online (Sandbox Code Playgroud)
这是可行的还是我过分简化地图?万一你没有达到目的,它的纹理贴图.
mat*_*t_h 25
许多C实现支持tsearch(3)或hsearch(3).tsearch(3)是一个二叉树,你可以提供一个比较器回调.我认为这就像你要去std :: map一样近.
这是一些c99示例代码
#include <search.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
typedef struct
{
int key;
char* value;
} intStrMap;
int compar(const void *l, const void *r)
{
const intStrMap *lm = l;
const intStrMap *lr = r;
return lm->key - lr->key;
}
int main(int argc, char **argv)
{
void *root = 0;
intStrMap *a = malloc(sizeof(intStrMap));
a->key = 2;
a->value = strdup("two");
tsearch(a, &root, compar); /* insert */
intStrMap *find_a = malloc(sizeof(intStrMap));
find_a->key = 2;
void *r = tfind(find_a, &root, compar); /* read */
printf("%s", (*(intStrMap**)r)->value);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
小智 17
你为什么不直接包装一个C接口std::map?即在自己的模块中编写一些C++函数:
typedef std::map<int, char*> Map;
extern "C" {
void* map_create() {
return reinterpret_cast<void*> (new Map);
}
void map_put(void* map, int k, char* v) {
Map* m = reinterpret_cast<Map*> (map);
m->insert(std::pair<int, char*>(k, v));
}
// etc...
} // extern "C"
Run Code Online (Sandbox Code Playgroud)
然后链接到您的C应用程序.
这当然是一种可能的实施方式.您可能想要考虑如何实现索引以及将产生的性能影响.例如,您可以将intKey列表作为键的排序列表.查找密钥将是O(log N)时间,但插入新项目将是O(N).
您可以将其实现为树(如std :: map),然后您将进行O(log N)插入和查找.
另一个替代方案是将其实现为哈希表,假设良好的哈希函数和足够稀疏的intKey数组,它将具有更好的运行时性能.
| 归档时间: |
|
| 查看次数: |
25667 次 |
| 最近记录: |