c++ - 当我尝试将索引分配给 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 进行比较是有效的,但显然情况并非如此。如果有人能指出我将如何去做这样的事情的正确方向,我将不胜感激。谢谢你。
解决方案
回复: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
。
推荐阅读
- python-3.x - bert-extractive-summarizer 未返回预期的句子数
- angular - 通过扩展运算符破坏模板渲染将属性添加到 Angular 应用程序中的数组
- python - 如何截取元素的屏幕截图并将其保存为 pdf?
- powershell - 使用 rename-item 命令覆盖现有文件?
- python - 如何将行中的每个值移动一个位置,移动数组中的一个位置?
- macos - 如何更改“make”命令设置以在 mac os 上编译 C++ 代码
- javascript - 颤振网页HTML Js
- python - 我必须使用哪个 pvlib 函数来获得每年的平面内照射,就像我使用 PVGIS 中的界面获得的那样?
- android - 无法初始化 viewmodel Dagger + 扩展功能
- spring-data-jpa - 为什么 CrudRepository 和 JpaRepository 的 findAll 方法返回的数据类型不同?