3
已解决
薛乘志
初级启示者
初级启示者
#include <assert.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
size_t len;
size_t typ_siz;
void *data;
} __do_vector, *vector_t;
vector_t __do_vector_new(size_t siz) {
vector_t vec = (vector_t)malloc(sizeof(__do_vector));
vec->len = 0;
vec->typ_siz = siz;
vec->data = malloc(1);
return vec;
}
void __do_vector_free(vector_t vec) {
free(vec->data);
free(vec);
}
void __do_vector_push_back(vector_t vec, const void *dat) {
vec->data = realloc(vec->data, (vec->len + 1) * vec->typ_siz);
memcpy(vec->data + vec->len * vec->typ_siz, dat, vec->typ_siz);
vec->len++;
}
void __do_vector_pop_back(vector_t vec) {
assert(vec->len > 0);
vec->data = realloc(vec->data, (vec->len - 1) * vec->typ_siz);
vec->len--;
}
void __do_vector_erase(vector_t vec, size_t idx) {
assert(idx >= 0);
assert(idx < vec->len);
for (size_t i = idx + 1; i < vec->len; i++) {
memcpy(vec->data + (i - 1) * vec->typ_siz, vec->data + i * vec->typ_siz, vec->typ_siz);
}
__do_vector_pop_back(vec);
}
#define vec_new(type) (__do_vector_new(sizeof(type)))
#define vec_free(vec) (__do_vector_free(vec))
#define vec_pushb(vec, data) (__do_vector_push_back(vec, data))
#define vec_popb(vec) (__do_vector_pop_back(vec))
#define vec_erase(vec, idx) (__do_vector_erase(vec, idx))
#define vec_get(vec, idx) (vec->data + idx * vec->typ_siz)
#define vec_getv(type, vec, idx) (*(type *)vec_get(vec, idx))
#define vec_size(vec) (vec->len)
#include <stdio.h>
int main() {
vector_t arr = vec_new(int);
for (int i = 100; i >= 1; i--) {
vec_pushb(arr, &i);
}
vec_erase(arr, 0);
vec_popb(arr);
vec_erase(arr, vec_size(arr) - 1);
for (int i = 0; i < vec_size(arr); i++) {
printf("%d: %d\n", i, vec_getv(int, arr, i));
}
vec_free(arr);
return 0;
}
纯C语言,不是C++哦(当然C++也能用)
薛乘志在2023-03-17 21:39:30追加了内容