Last active
July 5, 2019 12:35
-
-
Save wsgac/07a7ed8e93d6c3b4251ef9a680904438 to your computer and use it in GitHub Desktop.
Simple vector implementation in C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdlib.h> | |
| #include "vector.h" | |
| vector make_vector() { | |
| vector vec = { | |
| (int*)malloc(BUFSIZE*sizeof(int)), | |
| BUFSIZE, | |
| 0 | |
| }; | |
| return vec; | |
| } | |
| void reallocate(vector* vec) { | |
| int* new_buf = (int*)malloc(2*vec->bufsize*sizeof(int)); | |
| for (int i = 0; i < vec->bufsize; i++) | |
| new_buf[i] = vec->buffer[i]; | |
| vec->bufsize *= 2; | |
| free(vec->buffer); | |
| vec->buffer = new_buf; | |
| } | |
| void push(vector* vec, int el) { | |
| vec->buffer[vec->ptr++] = el; | |
| if (vec->ptr == vec->bufsize) | |
| reallocate(vec); | |
| } | |
| int pop(vector* vec) { | |
| return vec->buffer[--vec->ptr]; | |
| } | |
| int size(vector* vec) { | |
| return vec->ptr; | |
| } | |
| int peek(vector* vec) { | |
| return vec->buffer[vec->ptr-1]; | |
| } | |
| int empty(vector* vec) { | |
| return size(vec) == 0; | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| typedef struct | |
| { | |
| int* buffer; | |
| int bufsize; | |
| int ptr; | |
| } vector; | |
| vector make_vector(); | |
| void push(vector* vec, int el); | |
| int pop(vector* vec); | |
| int size(vector* vec); | |
| int peek(vector* vec); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment