Home >Backend Development >C++ >How to use vector's delete function in C
The remove usage of vector in C requires specific code examples
Introduction: vector in C language is a dynamic array whose size can be adjusted at runtime . It is a very commonly used data structure used to store and manipulate multiple objects. In practical applications, we often need to insert new elements into vectors or delete existing elements. This article will introduce in detail the use of vector remove in C language and give corresponding code examples.
There are two parameters in the function prototype, the first parameter is the vector pointer, The second parameter is the index of the element to be deleted. This index starts counting from 0 and represents the position of the element to be deleted in the vector.
#include <stdio.h> #include <stdlib.h> // 定义vector结构体 typedef struct { int *data; // 存储元素的数组 int size; // 当前元素个数 int capacity; // 容量 } vector; // 初始化vector void initVector(vector *v) { v->size = 0; v->capacity = 4; v->data = (int *)malloc(sizeof(int) * v->capacity); } // 向vector中插入元素 void insert(vector *v, int value) { // 如果当前元素个数等于容量,需要重新分配内存 if (v->size == v->capacity) { v->capacity *= 2; v->data = (int *)realloc(v->data, sizeof(int) * v->capacity); } v->data[v->size] = value; v->size++; } // 删除vector中的元素 void remove(vector *v, int index) { // 检查索引是否合法 if (index < 0 || index >= v->size) { printf("Invalid index"); return; } // 将后面的元素向前移动 for (int i = index; i < v->size - 1; i++) { v->data[i] = v->data[i + 1]; } v->size--; // 如果元素个数小于容量的一半,缩小容量 if (v->size <= v->capacity / 2) { v->capacity /= 2; v->data = (int *)realloc(v->data, sizeof(int) * v->capacity); } } int main() { vector v; initVector(&v); // 向vector中插入元素 insert(&v, 1); insert(&v, 2); insert(&v, 3); insert(&v, 4); // 打印vector中的元素 printf("Before remove: "); for (int i = 0; i < v.size; i++) { printf("%d ", v.data[i]); } printf(" "); // 删除vector中的元素 remove(&v, 1); // 打印删除后的vector中的元素 printf("After remove: "); for (int i = 0; i < v.size; i++) { printf("%d ", v.data[i]); } printf(" "); return 0; }
Code description:
Summary:
This article introduces the use of remove vector in C language and gives corresponding code examples. Through this example, we can clearly see how to insert elements into the vector, how to delete elements, and handle the corresponding memory management. These operations are what we often encounter in actual projects. Mastering the use of this data structure is very helpful for C language programmers.
The above is the detailed content of How to use vector's delete function in C. For more information, please follow other related articles on the PHP Chinese website!