首页 > 解决方案 > 当我尝试将索引分配给 nullptr 时,指向数组抛出错误的指针

问题描述

班级:

template <class T>
class vectorADT
{
public:
//default constructor
vectorADT();
//destructor
~vectorADT();

//push data to the front of the vector
void push_front(T data);
//push data to the rear of the vector
void push_back(T value);
void insert(int position, T value);
//remove data from the front of the vector
void remove_front();
//remove data from the rear of the vector
void remove_rear();
//return the front of the vector
T getFront();
//return the rear of the vector
T getRear();
//check if vector is full
bool isFull();
//create a new vector with more space
T *resize(T *prevSizePtr);
//return the size of the vector
int size();
//check if the vector is empty
bool isEmpty();
//print the vectors data
void print();

private:
T *vectPtr;
T array[4] = {};
int front;
int rear;
int vectSize;
};

构造函数:

template <class T>
vectorADT<T>::vectorADT()
{
front = 0;
rear = -1;
vectSize = 4;
vectPtr = array;
}

上课方法:

template <class T>
void vectorADT<T>::push_front(T data)
{
if (vectPtr[0] == nullptr)
{
    vectPtr[front] = data;
}

front++;
}

我之前问了一个问题,但我仍然对它的工作原理感到困惑。我希望能够检查我的数组是否有 nullptr 作为值,这样我就知道该索引是否为空,如果是,我可以为该索引分配一些数据。每当我尝试与 nullptr 进行比较时,都会收到许多关于 operator== 的错误。我认为当我执行 T array[4] = {} 时,它会将所有索引初始化为 nullptr 或零,从而使将该索引与 nullptr 进行比较是有效的,但显然情况并非如此。如果有人能指出我将如何去做这样的事情的正确方向,我将不胜感激。谢谢你。

标签: c++c++17

解决方案


回复:I want to be able to check if my array has nullptr as a value, that way I know whether that index is empty-你真的不需要知道。您应该维护一个size向量,它会告诉您是否有可用的插槽以及它们在哪里。你所说vectSize的其实是它的capacity


推荐阅读