How to replicate vector in c?

后端 未结 6 1068
一生所求
一生所求 2020-11-29 19:48

In the days before c++ and vector/lists, how did they expand the size of arrays when they needed to store more data?

6条回答
  •  独厮守ぢ
    2020-11-29 20:30

    Vector and list aren't conceptually tied to C++. Similar structures can be implemented in C, just the syntax (and error handling) would look different. For example LodePNG implements a dynamic array with functionality very similar to that of std::vector. A sample usage looks like:

    uivector v = {};
    uivector_push_back(&v, 1);
    uivector_push_back(&v, 42);
    for(size_t i = 0; i < v.size; ++i)
        printf("%d\n", v.data[i]);
    uivector_cleanup(&v);
    

    As can be seen the usage is somewhat verbose and the code needs to be duplicated to support different types.

    nothings/stb gives a simpler implementation that works with any types, but compiles only in C:

    double *v = 0;
    sb_push(v, 1.0);
    sb_push(v, 42.0);
    for(int i = 0; i < sb_count(v); ++i)
        printf("%g\n", v[i]);
    sb_free(v);
    

    A lot of C code, however, resorts to managing the memory directly with realloc:

    void* newMem = realloc(oldMem, newSize);
    if(!newMem) {
        // handle error
    }
    oldMem = newMem;
    

    Note that realloc returns null in case of failure, yet the old memory is still valid. In such situation this common (and incorrect) usage leaks memory:

    oldMem = realloc(oldMem, newSize);
    if(!oldMem) {
        // handle error
    }
    

    Compared to std::vector and the C equivalents from above, the simple realloc method does not provide O(1) amortized guarantee, even though realloc may sometimes be more efficient if it happens to avoid moving the memory around.

提交回复
热议问题