A good C equivalent of STL vector?

后端 未结 7 1902
悲&欢浪女
悲&欢浪女 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:19

    qLibc implements a vector in pure C. The data structure allows it to store any type of object like (void *object) and it provides convenient wrappers for string, formatted string and integer types.

    Here's a sample code for your idea.

    qvector_t *vector = qvector(QVECTOR_OPT_THREADSAFE);
    vector->addstr(vector, "Hello");
    vector->addstrf(vector, "World %d", 123);
    char *finalstring = vector->tostring(vector);
    
    printf("%s", finalstring);
    free(finalstring)
    vector->free(vector);
    

    for object type:

    int a = 1, b = 2;
    qvector_t *vector = qvector(QVECTOR_OPT_THREADSAFE);
    vector->add(vector, (void *)&a, sizeof(int));
    vector->add(vector, (void *)&b, sizeof(int));
    int *finalarray = vector->toarray(vector);
    
    printf("a = %d, b = %d", finalarray[0], finalarray[1]);
    free(finalarray)
    vector->free(vector);
    

    Note) I made this sample code just for your reference, copying from its example code. it might have typo errors.

    You can check out the Full API reference at http://wolkykim.github.io/qlibc/

提交回复
热议问题