一个好的C等价的STL载体?

Chr*_*fer 17 c c89

我注意到在我们的代码库中的几个地方,我们使用动态扩展数组,即一个与元素计数器和"max elements"值相结合的基本数组.

我想要做的是用通常的数据结构和实用程序函数替换它们,这是出于通常的面向对象的原因.数组元素可以是基本数据类型或结构,我需要快速随机访问元素,最好是类型安全的实现.

所以,基本上,我想使用的是STL向量,但代码库仅限于C89所以我必须提出其他的东西:-)

我给了它一些想法并掀起了这个初稿,只是为了展示我的目标:

/* Type-safe dynamic list in C89 */

#define list_declare(type) typedef struct _##type##_list_t { type * base_array; size_t elements; size_t max_size; } type##_list_t
#define list(type) type##_list_t
#define list_new(type, initial_size) { calloc(initial_size, sizeof(type)), 0, initial_size }
#define list_free(list) free(list.base_array)
#define list_set(list, place, element) if ( list.elements < list.max_size ) { list.base_array[place] = element; } else { /* Array index out of bounds */ }
#define list_add(list, element) if ( list.elements < list.max_size ) { list.base_array[list.elements++] = element; } else { /* Expand array then add */ }
#define list_get(list, n) list.base_array[n]

/* Sample usage: */

list_declare(int);

int main(void)
{
    list(int) integers = list_new(int, 10);
    printf("list[0] = %d\n", list_get(integers, 0));
    list_add(integers, 4);
    printf("list[0] = %d\n", list_get(integers, 0));
    list_set(integers, 0, 3);
    printf("list[0] = %d\n", list_get(integers, 0));
    list_free(integers);

    return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)

......但是,必须有其他人以前做过这件事.我知道FreeBSD sys/queue.h对一些不同队列的类似概念的实现,但是我找不到类似于数组的东西.

这里有人更聪明吗?

lun*_*orn 9

glib提供了一个GArray类型,它实现了一个动态增长的数组.如果你可以使用外部第三方库,glib几乎总是作为C的"标准"库的一个很好的选择.它为所有基本数据结构,unicode字符串,日期和时间值等提供类型.

  • @christoffer:Generic,但是类型安全的容器不能用C实现.C的类型系统太原始,不支持任何类型的泛型类型或模板.C只有通用的东西是void指针,这些都不是类型安全的.你必须习惯这样一个事实,即C只是一种弱类型的语言:) (7认同)