Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- What's the best c implementation of the C vector?
- int *create_vector(size_t n) {
- return malloc(n * sizeof(int));
- }
- void delete_vector(int *v) {
- free(v);
- }
- int *resize_vector(int *v, size_t n) {
- return realloc(v, n * sizeof(int));
- /* returns NULL on failure here */
- }
- typedef struct {
- size_t size;
- int *data;
- } int_vector;
- int_vector *create_vector(size_t n) {
- int_vector *p = malloc(sizeof(int_vector));
- if(p) {
- p->data = malloc(n * sizeof(int));
- p->size = n;
- }
- return p;
- }
- void delete_vector(int_vector *v) {
- if(v) {
- free(v->data);
- free(v);
- }
- }
- size_t resize_vector(int_vector *v, size_t n) {
- if(v) {
- int *p = realloc(v->data, n * sizeof(int));
- if(p) {
- p->data = p;
- p->size = n;
- }
- return v->size;
- }
- return 0;
- }
- int get_vector(int_vector *v, size_t n) {
- if(v && n < v->size) {
- return v->data[n];
- }
- /* return some error value, i'm doing -1 here,
- * std::vector would throw an exception if using at()
- * or have UB if using [] */
- return -1;
- }
- void set_vector(int_vector *v, size_t n, int x) {
- if(v) {
- if(n >= v->size) {
- resize_vector(v, n);
- }
- v->data[n] = x;
- }
- }
- int_vector *v = create_vector(10);
- set_vector(v, 0, 123);
- struct element{
- void* item;
- element* next;
- element* previous;
- }
Add Comment
Please, Sign In to add comment