简体   繁体   English

将元素插入结构向量

[英]Insert element into struct vector

I want to initialize a struct using a function and also insert into it as seen below.我想使用 function 初始化一个结构,并将其插入如下所示。 I want to initialize the array dynamically I want to declare two struct vectors, one dynamically and the other statically我想动态初始化数组 我想声明两个结构向量,一个是动态的,另一个是静态的

Your initialize() function is not allocating any memory for the array, and it is also not initializing the current_size to the correct value.您的initialize() function 没有为数组分配任何 memory ,它也没有将current_size初始化为正确的值。 It needs to look like this instead:它需要看起来像这样:

void initialize(vector &vec, int size){
    vec.current_size = 0;
    vec.array = new int[size];
    vec.max_size = size;
}

And then you need a function to free the array when you are done using it, eg:然后你需要一个 function 在你使用完数组后释放它,例如:

void finalize(vector &vec){
    delete[] vec.array;
    vec.current_size = 0;
    vec.max_size = 0;
}

Also, your insert() function should be updated to avoid a buffer overflow once the array fills up to its max capacity:此外,您的insert() function 应该更新以避免一旦数组填满其最大容量时缓冲区溢出:

void insert( vector &vec, int element){
    if (vec.current_size < vec.max_size){
        vec.array[vec.current_size] = element;
        vec.current_size++;
    }
}

If needed, this would also allow you to grow the array instead:如果需要,这也将允许您增加数组:

void insert( vector &vec, int element){
    if (vec.current_size == vec.max_size){
        int new_max = vec.max_size * 2;
        int *new_array = new int[new_max];
        for(int i = 0; i < vec.current_size; ++i){
            new_array[i] = vec.array[i];
        }
        delete[] vec.array;
        vec.array = new_array;
        vec.max_size = new_max;
    }
    vec.array[vec.current_size] = element;
    vec.current_size++;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM