Home Backend Development C++ How to use vector's delete function in C

How to use vector's delete function in C

Feb 18, 2024 am 11:29 AM
c vector remove typedef

How to use vectors 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.

  1. vector's remove function prototype: void remove(vector *v, int index)

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.

  1. Sample code:
#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;
}
Copy after login

Code description:

  • Realize the function of vector by defining a structure. The structure contains a pointer data of type int, which represents a dynamic array. There are also size and capacity fields, which respectively indicate the current number of elements and capacity.
  • The initVector function is used to initialize the vector, set both size and capacity to 0, and allocate initial memory for data.
  • The insert function is used to insert elements into vector. If the current number of elements is equal to the capacity, memory needs to be reallocated.
  • Theremove function is used to delete elements in vector. According to the given index, the following elements are moved forward and the capacity is reduced.
  • In the sample code, four elements are first inserted into the vector, and then the element with index 1 is deleted.

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Usage of typedef struct in c language Usage of typedef struct in c language May 09, 2024 am 10:15 AM

typedef struct is used in C language to create structure type aliases to simplify the use of structures. It aliases a new data type to an existing structure by specifying the structure alias. Benefits include enhanced readability, code reuse, and type checking. Note: The structure must be defined before using an alias. The alias must be unique in the program and only valid within the scope in which it is declared.

VSCode and VS C++ IntelliSense not working or picking up libraries VSCode and VS C++ IntelliSense not working or picking up libraries Feb 29, 2024 pm 01:28 PM

VS Code and Visual Studio C++ IntelliSense may not be able to pick up libraries, especially when working on large projects. When we hover over #Include&lt;wx/wx.h&gt;, we see the error message "CannotOpen source file 'string.h'" (depends on "wx/wx.h") and sometimes, autocomplete Function is unresponsive. In this article we will see what you can do if VSCode and VSC++ IntelliSense are not working or extracting libraries. Why doesn't my Intellisense work in C++? When working with large files, IntelliSense sometimes

Understanding Memory Management of C++ Function Pointers: Avoiding Pointer Traps Understanding Memory Management of C++ Function Pointers: Avoiding Pointer Traps Apr 29, 2024 pm 09:03 PM

When using function pointers in C++, memory management must be carefully considered to avoid pitfalls. These traps include dangling pointers (pointing to functions outside their scope) and wild pointers (function pointers that are never initialized or set to nullptr). To avoid these pitfalls, follow these best practices: always initialize function pointers, manage memory carefully, and use smart pointers. This way you can use function pointers safely and avoid falling into pointer traps.

How to write simple fireworks code in C language How to write simple fireworks code in C language Apr 13, 2024 pm 09:18 PM

To write a simple firework code in C, you need to follow these steps: Include header files and libraries. Define constants and macros. Create a particle data structure. Declare global variables. Initialize the fireworks particles in the main() function. Update the particle's position and velocity in the game loop and draw them. Check for and destroy particles that have reached their end of life.

The difference between typedef struct and struct in c++ The difference between typedef struct and struct in c++ May 01, 2024 am 11:36 AM

The difference between typedef struct and struct: typedef struct creates an alias of a structure type, while struct defines a new structure type. The alias created by typedef struct can be used after it is declared, while the structure defined by struct can be used after it is defined. Neither typedef struct nor struct creates additional storage space.

Transform code with C++ function pointers: improve efficiency and reusability Transform code with C++ function pointers: improve efficiency and reusability Apr 29, 2024 pm 06:45 PM

Function pointer technology can improve code efficiency and reusability, specifically as follows: Improved efficiency: Using function pointers can reduce repeated code and optimize the calling process. Improve reusability: Function pointers allow the use of general functions to process different data, improving program reusability.

Deep Dive: How to Convert PHP Code to C Deep Dive: How to Convert PHP Code to C Mar 12, 2024 pm 01:36 PM

PHP is a scripting language widely used in web development, while C language is a low-level programming language. In some specific scenarios, it may be necessary to convert PHP code into C language to improve program performance and operating efficiency. This article will delve into how PHP code is converted to C language and give specific code examples. Reasons for converting PHP code to C language First, let us take a look at why it is sometimes necessary to convert PHP code to C language? PHP is an interpreted language, and the execution code needs to be interpreted line by line during runtime.

In-depth understanding of the similarities and differences between C++ and C languages In-depth understanding of the similarities and differences between C++ and C languages Mar 26, 2024 am 09:36 AM

C++ and C are two popular programming languages ​​that are similar in many ways, but also have many significant differences. This article will delve into the similarities and differences between C++ and C languages, and illustrate their differences through specific code examples. 1. Basic syntax and structural differences 1.1 Data type definition In C language, when defining a variable, you need to declare the data type first, for example: intnum; in C++, you can initialize the variable at the same time as defining it, for example: intnum=10; 1.2 function definition

See all articles