用C++写一个vector
时间: 2023-06-10 12:08:39 浏览: 103
在C语言中,没有直接支持向量的数据类型,但可以通过结构体和动态内存分配来实现类似的功能。以下是一个简单的向量结构体和相应的函数实现:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int* data;
int size;
int capacity;
} Vector;
void vector_init(Vector* vec) {
vec->data = NULL;
vec->size = 0;
vec->capacity = 0;
}
void vector_append(Vector* vec, int value) {
if (vec->size == vec->capacity) {
int new_capacity = vec->capacity == 0 ? 1 : vec->capacity * 2;
int* new_data = (int*)realloc(vec->data, new_capacity * sizeof(int));
if (new_data == NULL) {
printf("Error: Failed to allocate memory for vector.\n");
exit(1);
}
vec->data = new_data;
vec->capacity = new_capacity;
}
vec->data[vec->size++] = value;
}
int vector_get(Vector* vec, int index) {
if (index < 0 || index >= vec->size) {
printf("Error: Index out of bounds.\n");
exit(1);
}
return vec->data[index];
}
void vector_set(Vector* vec, int index, int value) {
if (index < 0 || index >= vec->size) {
printf("Error: Index out of bounds.\n");
exit(1);
}
vec->data[index] = value;
}
void vector_free(Vector* vec) {
free(vec->data);
vec->data = NULL;
vec->size = 0;
vec->capacity = 0;
}
```
使用示例:
```c
int main() {
Vector vec;
vector_init(&vec);
vector_append(&vec, 1);
vector_append(&vec, 2);
vector_append(&vec, 3);
printf("Vector size: %d\n", vec.size);
printf("Vector capacity: %d\n", vec.capacity);
printf("Vector elements:");
for (int i = 0; i < vec.size; i++) {
printf(" %d", vector_get(&vec, i));
}
printf("\n");
vector_set(&vec, 1, 4);
printf("Vector elements:");
for (int i = 0; i < vec.size; i++) {
printf(" %d", vector_get(&vec, i));
}
printf("\n");
vector_free(&vec);
return 0;
}
```
输出结果:
```
Vector size: 3
Vector capacity: 4
Vector elements: 1 2 3
Vector elements: 1 4 3
```
阅读全文