c++ - 程序 _free_dbg(block, _UNKNOWN_BLOCK) 出错
问题描述
这是一本书的问题,我收到以下错误:_free_dbg(block, _UNKNOWN_BLOCK)
下面是一个类的实现代码:
template<class T>
Set<T>::Set(): items(NULL), num_items(0)
{
}
template<class T>
Set<T>::Set(const Set<T>& other)
{
num_items = other.num_items;
items = other.to_array();
}
template<class T>
Set<T>::~Set()
{
if (items != NULL)
{
delete[] items;
}
}
template<class T>
void Set<T>::operator= (const Set<T>& right_side)
{
if (items != NULL)
{
delete[] items;
}
num_items = right_side.num_items;
items = right_side.to_array();
}
template<class T>
void Set<T>::add(T item)
{
if (!contains(item))
{
T *new_items = new T[num_items + 1];
for (int i = 0; i < num_items; i++)
{
new_items[i] = items[i];
}
new_items[num_items] = item;
if (num_items > 0)
{
delete[] items;
}
num_items++;
items = new_items;
}
}
template<class T>
void Set<T>::remove(T item)
{
if (contains(item))
{
T *copy = NULL;
if (num_items > 1)
{
copy = new T[num_items - 1];
for (int i = 0, j = 0; i < num_items; i++)
{
if (items[i] != item)
{
copy[j] = items[i];
j++;
}
}
}
delete[] items;
items = copy;
num_items--;
}
}
template<class T>
int Set<T>::size() const
{
return num_items;
}
template<class T>
bool Set<T>::contains(T item) const
{
for (int i = 0; i < num_items; i++)
{
if (items[i] == item)
{
return true;
}
}
}
template<class T>
T *Set<T>::to_array() const
{
T *copy = NULL;
if (num_items > 0)
{
copy = new T[num_items];
for (int i = 0; i < num_items; i++)
{
copy[i] = items[i];
}
return copy;
}
}
我查了这个问题,我相信是导致这个问题的 delete[] 部分。有人可以告诉我错误是什么,我该如何纠正?
解决方案
好的,我已经解决了这个问题。
将contains
函数替换为Set.cpp
:
template<class T>
bool Set<T>::contains(T item) const
{
for (int i = 0; i < num_items; i++)
{
if (items[i] == item)
{
return true;
}
}
return false;
}
然后用你的print_set
函数main.cpp
替换这个:
template<class T>
void output_set(Set<T> myset)
{
T *ptr = myset.to_array();
if (ptr != NULL)
{
for (int i = 0; i < myset.size(); i++) {
cout << ptr[i] << endl; }
}
else {
cout << "The set is empty." << endl;
}
}
解释
在函数中,找不到时contains
忘记返回。这意味着在这种情况下该函数没有返回任何值,并且当您在将项目添加到检查有项目的语句时调用此函数时,此操作失败。false
item
Set
if
现在对于该功能,即使您没有完成打印,您也print_set
删除了循环中的每次,因此第一项打印正确,但其余项没有打印。ptr
推荐阅读
- javascript - 如何在每个表格行的末尾添加按钮?
- c - 在 linux 主机上遇到“浮点异常”错误
- c# - OData ASP.NET Core Web API Get 方法 - 传递多个参数
- symfony - RabbitMqBundle 上的队列优先级问题
- amazon-web-services - 使用 Redis 访问 AWS 上的公共 DNS
- swift - Swift CoreLocation
- python - 使用 openai 健身房(二十一点)制作 AI
- java - 使用 REST 在 Pod 之间进行 Kubernetes 通信
- c# - 在 c# 中设置 out 参数时出现 NullReferenceException
- sql - 查询基于 N-1 行聚合值