C++ vector 的方法
时间: 2023-11-04 21:14:30 浏览: 34
C 语言中没有内置的 vector 类型,但可以使用结构体和动态内存分配实现类似于 vector 的功能。以下是一个简单的实现(仅供参考):
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int *data;
int size;
int capacity;
} Vector;
void vector_init(Vector *v) {
v->data = NULL;
v->size = 0;
v->capacity = 0;
}
void vector_push_back(Vector *v, int value) {
if (v->size == v->capacity) {
v->capacity = v->capacity == 0 ? 1 : v->capacity * 2;
v->data = (int *)realloc(v->data, v->capacity * sizeof(int));
}
v->data[v->size++] = value;
}
int vector_at(Vector *v, int index) {
if (index < 0 || index >= v->size) {
printf("Index out of range\n");
exit(1);
}
return v->data[index];
}
void vector_free(Vector *v) {
free(v->data);
v->data = NULL;
v->size = 0;
v->capacity = 0;
}
```
使用示例:
```c
int main() {
Vector v;
vector_init(&v);
vector_push_back(&v, 1);
vector_push_back(&v, 2);
vector_push_back(&v, 3);
printf("Size: %d\n", v.size); // Size: 3
printf("Capacity: %d\n", v.capacity); // Capacity: 4
printf("Element at index 1: %d\n", vector_at(&v, 1)); // Element at index 1: 2
vector_free(&v);
return 0;
}
```
注意,这只是一个简单的实现,还有很多需要改进的地方,比如添加删除元素的方法等。建议在项目中使用成熟的第三方库,如 GLib 的 GArray 类型。