简体   繁体   English

为什么这会给我造成访问冲突? (C ++)

[英]Why is this giving me an access violation? (C++)

I'm building a vector class for my data structures class, and I can't figure out why this is throwing an exception. 我正在为我的数据结构类构建一个向量类,但我不知道为什么会引发异常。 Here's the complete Vector.h file: 这是完整的Vector.h文件:

#include <iostream>

using namespace std;

template <class T>
class Vector {
private:

  // not yet implemented
  Vector(const Vector& v);
  Vector& operator=(const Vector& v);
  T * Tarray;
  int arraySize;
  int currentSize;

public:

Vector() {
    arraySize = 2;
    currentSize = 0;
    Tarray = new T[arraySize];
};
~Vector() {
    delete[] Tarray;
};

void push_back(const T &e) {
    ++currentSize;
    if (currentSize > arraySize) {
        arraySize *= 4;
        T * temp = new T[arraySize];

        for (int i = 0; i < currentSize; i++) {
            temp[i] = Tarray[i];
        }

        delete[] Tarray;
        Tarray = new T[arraySize];

        for (int j = 0; j < currentSize; j++) {
            Tarray[j] = temp[j];
        }

        delete[] temp;

        Tarray[currentSize - 1] = e;
    }

    else {
        Tarray[currentSize - 1] = e;
    }
};

void print() {
    for (int i = 0; i < currentSize; i++) {
        cout << Tarray[i] << "  ";
    }

};

int getCurrentSize() {
    return currentSize;
};

int getArraySize() {
    return arraySize;
};

// Not yet implemented
void pop_back();

int size() const;

T& operator[](int n);


};

And here's my complete main.cpp I was using to test it. 这是我用来测试的完整main.cpp。

#include "Vector.h"
#include <iostream>
#include <string>

using namespace std;

int main() {
char c;

string * temp = new string[8];


Vector<string> newVector;

for (int i = 0; i < 8; i++) {
    newVector.push_back("Hello world");
    newVector.push_back("Hello world");
}

newVector.print();
cout << endl << "Current Size: " << newVector.getCurrentSize();
cout << endl << "Array Size: " << newVector.getArraySize();
cin >> c;
}

I would rewrite push_back as follows: 我将重写push_back ,如下所示:

void push_back(const T &e) {
    if (currentSize+1 > arraySize) {
        arraySize *= 4;
        T * temp = new T[arraySize];

        for (int i = 0; i < currentSize; i++) {
            temp[i] = Tarray[i];
        }

        delete[] Tarray;
        Tarray = temp;
    }
    Tarray[currentSize] = e;
    ++currentSize;
};

Changes are: 更改为:

  • Don't update currentSize until after you have copied the contents (thus not going out of bounds in Tarray ). 在复制内容之前,不要更新currentSize (这样就不会超出Tarray的范围)。
  • Don't allocate and copy twice. 不要分配和复制两次。 Just assign Tarray to temp after deleting it. 只需在删除Tarray后将其分配给temp
  • Only stick element into Tarray in one place. 只能将元素粘到一个Tarray中。
  • Update currentSize after, to avoid having to do -1 (It does require a single +1 in the first if instead. 更新currentSize后,要避免做-1 (它确实需要一个+1第一if代替。

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

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