自定义矢量/动态数组C ++问题

问题描述

我正在尝试用C ++制作自己的向量,以便我能进一步了解它的工作原理! 这是代码

#pragma once

template<typename T>
class Vector {
public:
    Vector() {
        // allocate 2 elements
        ReAlloc(2);
    }

    void pushBack(const T& value) {
        if (m_Size >= m_Capacity) {
            ReAlloc(m_Capacity / 2);
        }
        m_Data[m_Size++] = value;
    }

    const T& operator[](size_t index) const {
        /*
        if (index >= m_Size) {
            // assert
        }
        */
        return m_Data[index];
    }

    T& operator[](size_t index) {
        /*
        if (index >= m_Size) {
            // assert
        }
        */
        return m_Data[index];
    }

    const size_t Size() const { return m_Size; }
    size_t Size() { return m_Size; }
private:
    T* m_Data = nullptr;
    size_t m_Size = 0;
    size_t m_Capacity = 0;
private:
    void ReAlloc(size_t newCapacity) {
        // 1. allocate a new block of memory
        // 2. copy/move old elements into the new block
        // 3. delete the old one

        T* newBlock = new T[newCapacity];
        if (newCapacity < m_Size) {
            m_Size = newCapacity;
        }
        for (size_t i = 0; i < m_Size; i++) {
            newBlock[i] = m_Data[i];
        }
        delete[] m_Data;
        m_Data = newBlock;
        m_Capacity = newCapacity;
    }
};

但是,当我尝试像这样从main.cpp使用它时:

#include <iostream>
#include <string>

#include "Vector.h"

#define print(x) std::cout << x
#define println(x) std::cout << x << std::endl

template<typename T>
void PrintVector(Vector<T>& vector) {
    for (size_t i = 0; i < vector.Size(); i++) {
        println(vector[i]);
    }
    println("------------------------------------------");
}

int main() {
    Vector<std::string> vector;
    vector.pushBack("Ahmed");
    vector.pushBack("C++");
    vector.pushBack("Vector");

    PrintVector(vector);
}

代码给了我这个输出

Ahmed
Vector
------------------------------------------
(process 7540) exited with code -1073740940.

这甚至都不是打印C ++,并且代码表现得很怪异,每当我尝试更改任何内容时,输出就会变得更加混乱,任何人都可以告诉我我做错了什么吗?! 谢谢 ! :)

解决方法

在您的firebase.auth().onAuthStateChanged(function(user) { if (user) { // User is signed in. } else { // User is signed out. } }); 函数中,当大小大于或等于容量时,您将执行以下操作:

pushBack

这没有意义。如果需要更多空间来添加元素,则应增加基础数组的容量,而不是将其减少一半。

您可能正在寻找:

ReAlloc(m_Capacity / 2);

这使基础容量增加了一倍。

这里工作正常,demo,没有任何段错误。