A good C equivalent of STL vector?

后端 未结 7 2173
悲&欢浪女
悲&欢浪女 2021-02-02 12:54

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.

7条回答
  •  感动是毒
    2021-02-02 13:33

    I'm using the following macro implementation without problems so far. It isn't a complete implementation but grows the array automatically :

    #define DECLARE_DYN_ARRAY(T) \
        typedef struct \
        { \
            T *buf; \
            size_t n; \
            size_t reserved; \
        } T ## Array;
    
    #define DYN_ARRAY(T) T ## Array
    
    #define DYN_ADD(array, value, errorLabel) DYN_ADD_REALLOC(array, value, errorLabel, realloc)
    
    #define DYN_ADD_REALLOC(array, value, errorLabel, realloc) \
        { \
            if ((array).n >= (array).reserved) \
            { \
                if (!(array).reserved) (array).reserved = 10; \
                (array).reserved *= 2; \
                void *ptr = realloc((array).buf, sizeof(*(array).buf)*(array).reserved); \
                if (!ptr) goto errorLabel; \
                (array).buf = ptr; \
            } \
            (array).buf[(array).n++] = value; \
        }
    

    To use you first write: DECLARE_DYN_ARRAY(YourType)

    To declare variables you write DYN_ARRAY(YourType) array = {0}.

    You add elements with DYN_ADD(array, element, errorLabel).

    You access elements with array.buf[i].

    You get the number of elements with array.n.

    When done you free it with free(array.buf) (or whatever function you used to allocate it.)

提交回复
热议问题