一个良好的等价的C STL向量的? [英] A good C equivalent of STL vector?

查看:160
本文介绍了一个良好的等价的C STL向量的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到,在我们的code基的几个地方,我们使用动态扩展阵列,即加上一个元素计数器和一个最大因素的价值基础数组。

I've noticed that at several places in our code base we use dynamically expanding arrays, i.e. a base array coupled with an element counter and a "max elements" value.

我想要做的是一个共同的数据结构和实用功能替换这些,对于通常的面向对象的原因。
数组元素可以是基本数据类型或结构,我需要快速随机访问元素,preferably一个类型安全的实现。

What I want to do is replace these with a common data structure and utility functions, for the usual object-oriented reasons. The array elements can be either basic data types or structs, I need fast random access to the elements, and preferably a type-safe implementation.

所以,基本上,我想用是一个STL向量,但code碱基被限制为C89,所以我必须想出别的东西: - )

So, basically, what I would like to use is an STL vector, but the code base is restricted to C89 so I have to come up with something else :-)

我给它一些思考刮起这个初稿,只是为了展示一下我的目标为:

I gave it some thought and whipped up this initial draft, just to show what I'm aiming at:

/* 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;
}

...但是,必须有别人谁曾这样做过。我知道在FreeBSD SYS / queue.h实施一些不同的队列类似的概念,但我找不到这样的数组什么。

...however, there must be someone else who has done this before. I'm aware of the FreeBSD sys/queue.h implementation of a similar concept for some different queues, but I can't find anything like that for arrays.

时有人在这里更聪明?

推荐答案

巧舌如簧提供 GArray < /一>型,它实现了一个动态增长的数组。如果您可以使用外部第三方库,油嘴几乎总是一个不错的选择,因为标准库C.它提供了类型所有的基本数据结构,为UNI code字符串,日期和时间值,等等

glib provides an GArray type, which implements a dynamically growing array. If you can use external 3rd party libraries, glib is almost always a good choice as "standard" library for C. It provides types for all basic data structures, for unicode strings, for date and time values, and so on.

这篇关于一个良好的等价的C STL向量的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆