简体   繁体   English

如何创建动态数组的 push_back function?

[英]How can i create push_back function of dynamic array?

Im trying to create this and add push back functionality.我正在尝试创建它并添加回推功能。 How can i do it?我该怎么做? I came up with this code but im very confused for 2 days because it gives this output - |我想出了这个代码,但我很困惑 2 天,因为它给出了这个 output - | -842150451 | -842150451 | -842150451 | -842150451 | -842150451 | -842150451 | -842150451 | -842150451 | -842150451 | -842150451 | -842150451 | -842150451 | -842150451 | -842150451 | -842150451 I will be thankful if someone can tell me how this function push_back should look or at least point me in the right direction. -842150451如果有人能告诉我这个 function push_back 应该如何看或至少为我指明正确的方向,我将不胜感激。 Also i would be thankful if you tell me where this code is doing wrong?如果你告诉我这段代码哪里做错了,我也会很感激?

 struct IntArray{
private:
    int k;

    int* first_cell;

    int size; // currently occupied elements
    int capacity = 8; // size of the allocated memory

public:
    void create() {
        first_cell = (int*)malloc(capacity * sizeof(int));
    }

    void random_numbers_fill(int limit) {

        srand(time(NULL));

        for (k = 0; k < capacity; k++) {

            first_cell[k] = rand() % limit;
        }

    }

    void push_back(int number) {

        if (size == capacity) {
            int* new_arr;
            capacity *= 2;
            new_arr = (int*)malloc(capacity * sizeof(int));
            for (k = 0; k < capacity; k++) {
                new_arr[k] = first_cell[k];
            }
            free(first_cell);
            first_cell = new_arr;
            first_cell[size] = number;
            size++;
        }

    }

    void print() {
        for (k = 0; k < capacity; k++) {
            printf("| %d ", first_cell[k]);
        }
    

First, create() should be changed into an actual constructor.首先,应将create()更改为实际的构造函数。 And you are missing a destructor to free the array, as well as copy/move constructors and copy/move assignment operators to manage the array (per the Rule of 3/5/0 ).而且您缺少用于释放数组的析构函数,以及用于管理数组的复制/移动构造函数和复制/移动赋值运算符(根据3/5/0 规则)。

Second, you should be using new[] instead of malloc() .其次,您应该使用new[]而不是malloc()

Third, regarding your push_back() , it is not a bad attempt, but it is buggy.第三,关于您的push_back() ,这不是一个糟糕的尝试,但它是错误的。 You are not adding the number to the array at all if the current size is less than the current capacity (and your constructor is not initializing size at all).如果当前size小于当前capacity (并且您的构造函数根本没有初始化size ),则根本不会将number添加到数组中。 And when you do resize + copy the array, you are copying too many int s from the old array.当你调整大小 + 复制数组时,你从旧数组中复制了太多的int The old array is size elements, but you are trying to copy the newly increased capacity elements from it.旧数组是size元素,但您正试图从中复制新增加的capacity元素。

With that said, try something more like this instead:话虽如此,请尝试更像这样的东西:

#include <iostream>
#include <algorithm>
#include <utility>

class IntArray{
private:
    int* first_cell = nullptr;
    int size = 0; // currently occupied elements
    int capacity = 8; // size of the allocated memory

public:
    IntArray()
    {
        first_cell = new int[capacity];
    }

    IntArray(const IntArray &src)
        : size(src.size), capacity(src.capacity)
    {
        first_cell = new int[capacity];
        std::copy_n(src.first_cell, size, first_cell);
    }

    IntArray(IntArray &&src)
        : first_cell(src.first_cell), size(src.size), capacity(src.capacity)
    {
        src.first_cell = nullptr;
        src.size = src.capacity = 0;
    }

    ~IntArray()
    {
        delete[] first_cell;
    }

    IntArray& operator=(IntArray rhs)
    {
        IntArray temp(std::move(rhs));
        std::swap(first_cell, temp.first_cell);
        std::swap(size, temp.size);
        std::swap(capacity, temp.capacity);
        return *this;
    }

    void push_back(int number)
    {
        if (size == capacity)
        {
            int new_cap = capacity * 2;
            int* new_arr = new int[new_cap];
            for (int k = 0; k < size; ++k) {
                new_arr[k] = first_cell[k];
            }
            delete[] first_cell;
            first_cell = new_arr;
            capacity = new_cap;
        }
        first_cell[size] = number;
        ++size;
    }

    void print() const
    {
        for (int k = 0; k < size; ++k) {
            std::cout << "| " << first_cell[k] << " ";
        }
    }
};

That being said, you should just get rid of your manual array and use std::vector<int> instead, as it handles all of these details for you, eg:话虽如此,您应该摆脱手动数组并改用std::vector<int> ,因为它会为您处理所有这些细节,例如:

#include <iostream>
#include <vector>

class IntArray{
private:
    std::vector<int> vec;

public:
    IntArray()
    {
        vec.reserve(8);
    }

    void push_back(int number)
    {
        vec.push_back(number);
    }

    void print() const
    {
        for (int number : vec) {
            std::cout << "| " << number << " ";
        }
    }
};

You never initialize size in create .您永远不会在create中初始化size

Your push_back has two problems.您的push_back有两个问题。 You don't copy the number that is pushed unless you grow the array (the last two statements should be outside the if block), and the condition in the for loop should compare with size , not capacity .除非增加数组(最后两个语句应该在if块之外),否则不要复制推送的数字,并且for循环中的条件应该与size进行比较,而不是capacity

print also has the wrong condition in the for loop. printfor循环中也有错误的条件。

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

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