Name: Anonymous 2016-07-20 3:56
Must support:
* Adding elements
* Regrowing
* Adding elements
* Regrowing
For example, the shortcut C-M-% is executed by pressing simultaneously four keys on my keyboard, each on a different side of the keyboard. Here is how to remap the associated command to C-c %.
though that would actually be more elegant than what C++ templates actually doNo, it wouldn't. C++ templates at least work correctly and efficiently. Ad hoc C shit knocked together by a hacker won't.
printarray()
function. It is written in portable ANSI C, and to the best of my knowledge is free of undefined behavior. If any call to malloc()
fails, it is reported to the user and the program quits. I however did not bother to check for failure of any other of the standard library functions included in the program.#include <stdio.h>
#include <stdlib.h>
typedef struct {
int *data;
unsigned long size;
} vector;
void vector_init(vector *v) {
v->data = NULL;
v->size = 0;
}
void vector_addelement(vector *v, int element) {
int *ptr = realloc(v->data, v->size + 1);
if(ptr == NULL) {
fputs("fatal runtime error: heap allocation failed", stderr);
exit(EXIT_FAILURE);
} else {
v->data = ptr;
v->data[v->size] = element;
v->size++;
}
}
void printvector(vector *v) {
unsigned long i;
for(i = 0; i < v->size; i++) {
printf("%d ", v->data[i]);
}
printf("\n");
}
int main(void) {
vector *vec = malloc(sizeof(vector));
if(vec == NULL) {
fputs("fatal runtime error: heap allocation failed", stderr);
exit(EXIT_FAILURE);
}
vector_init(vec);
vector_addelement(vec, 5);
vector_addelement(vec, 6);
vector_addelement(vec, 10);
printvector(vec); /* 5 6 10 */
vector_addelement(vec, 2);
vector_addelement(vec, 3);
printvector(vec); /* 5 6 10 2 3 */
printf("third element of vec is %d\n", vec->data[2]); /* should be 10 */
printf("there are %d elements in vec\n", vec->size); /* should be 5 */
return(EXIT_SUCCESS);
}
v.push_back(e);
all the time.realloc()
on every push_back()
/append()
, right? reserve()
, but actually seeing that used correctly --- or at all --- is rare.malloc()
and realloc()
anyway. Large fixed allocations go in static arrays, small static allocations go on the stack, and small dynamic allocations can either be treated as small static ones (if the upper limit is not too high) or a fixed heap allocation. They all have different characteristics and assuming std::vector is the best for all of those use-cases is just plain stupid.