EnQueue 方法在循环队列中未正确返回C++?
EnQueue method not returning correctly in C++ circular queue?
我只有不到 3 个月的编码经验,所以我开始使用 LeetCode 来构建超出学校分配的代码时间。
我正在努力尝试构建一个循环队列 (FIFO(,但它无法编译。我收到以下错误,我被难住了:
解决方案.cpp:在成员函数 enQueue 中 第 58 行:字符 2:错误:控制到达非无效函数的末尾 [-werror=返回类型] }
一件事:我被特别指示不要使用 std::queue 库,所以虽然我知道这可能会容易得多,但这不是一个选择。
我构建的完整代码如下:
class MyCircularQueue
{
private:
int* data = nullptr;
int size;
int capacity;
int front_p;
int rear_p;
public:
/** Initialize your data structure here. Set the size of the queue to be k. */
MyCircularQueue(int k)
{
data = new int[k];
size = 0;
capacity = k;
front_p = 0;
rear_p = 0;
}
/** Insert an element into the circular queue. Return true if the operation is successful. */
bool enQueue(int value)
{
if (!isFull() && isEmpty())
{
for (int i = 0; i < capacity; i++)
{
if (data[i] == 0)
{
data[i] = value;
size++;
front_p = data[i];
rear_p = data[i];
return true;
}
}
}
else if (!isFull())
{
for (int i = 0; i < capacity; i++)
{
if (data[i] == 0)
{
data[i] = value;
size++;
front_p = data[i];
rear_p = rear_p++;
return true;
}
}
}
else
{
return false;
}
}
/** Delete an element from the circular queue. Return true if the operation is successful. */
bool deQueue()
{
if (isEmpty())
{
return false;
}
else
{
front_p = front_p++;
return true;
}
}
/** Get the front item from the queue. */
int Front()
{
return front_p;
}
/** Get the last item from the queue. */
int Rear()
{
return rear_p;
}
/** Checks whether the circular queue is empty or not. */
bool isEmpty()
{
for (int i = 0; i < size; i++)
{
if (data[i] != 0)
{
return false;
}
else
return true;
}
}
/** Checks whether the circular queue is full or not. */
bool isFull()
{
if (size == capacity)
{
return true;
}
else
return false;
}
};
您收到该错误是因为通过enQueue
执行并不总是以return
语句结束。 从逻辑上讲,这可能永远不会发生,但编译器不知道这一点,因为它看到如果其中一个for
循环以i >= capacity
终止,您将不会遇到return
语句。
简单的解决方法是删除最后一个else
,以便return false;
始终在函数结束时执行。
}
return false;
}
相关文章:
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- 什么时候在C++中返回常量引用是个好主意
- 你能重载对象变量名本身返回的内容吗
- 为什么 Serial.println(<char[]>);返回随机字符?
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 如何获取std::result_of函数的返回类型
- QueryWorkingSet总是返回false
- (C++)分析树以计算返回错误值的简单算术表达式
- 访问者访问变体并返回不同类型时出错
- 如何返回一个类的两个对象相加的结果
- OpenInventor从9.8升级到10.4.2后,GLSL纹理返回零
- lower_bound()返回最后一个元素
- "throw expression code" 1e7 >返回 d 是什么?投掷标准::overflow_error( "too big" ) : d;意味 着?
- 奇怪的(对我来说)返回声明 - 在谷歌上找不到任何关于它的信息
- 如何取消对nullptr的屏蔽,返回正确的对象
- 奇怪的结构&GCC&clang(void*返回类型)
- 架构决策:返回std::future还是提供回调
- 从python中调用C++函数并获取返回值
- 矩阵向量乘法(cublasDgemv)返回零
- 为什么模板类中的对象不能返回值