c++ - Visual Studio C++ 运行时错误:抛出异常:读取访问冲突。_Pnext 为 0xDDDDDDE1
问题描述
我正在做一个家庭作业,我们应该使用基于哈希的链实现来实现一个集合。
我们将 C++ 的 forward_list 用于存储桶。
我们必须重载运算符 + 用于联合,* 用于交集,以及赋值运算符 (=)。但是每次我运行我的程序时,我都会收到这个错误。
Exception thrown: read access violation.
_Pnext was 0xDDDDDDE1.
这段代码给了我错误。特别是最后一行
SetT<int> setA;
SetT<int> setB;
SetT<int> setResult;
setA.Add(20);
setB.Add(20);
setResult = setA * setB;
我尝试调试,但没有帮助。它会毫无问题地通过 operator*,然后通过 operator=,退出,然后一旦我回到 main 进入下一行,它就会给我错误。
我也看了类似的问题,但我找不到我的程序崩溃的原因。
这些是类 SetT 的私有变量
forward_list<T>** buckets; // An array of forward_list's
// (ie, each index is a forward_list pointer)
int numBuckets;
int getHashIndex(const T& elem);
int numElems;
// Iterator variables
int currBucket; // what bucket is the iterator on?
mutable typename forward_list<T>::iterator bucketIter; // the iterator of the current bucket
这是添加的代码:
template<class T>
bool SetT<T>::Add(T elem)
{
// If the set already contains elem, do nothing
if (Contains(elem)) {
return false;
}
// Get the bucket index and add the element to the bucket.
currBucket = getHashIndex(elem);
buckets[currBucket]->push_front(elem);
numElems++;
return true;
// Extra credit: If the load factor becomes too large, change the number of buckets and rehash.
}
散列函数是我们的教授给的,他告诉我们不要碰它。
这是包含的代码:
template<class T>
bool SetT<T>::Contains(T elem)
{
// Use hash function to find the bucket, then check
// to see if elem is in the bucket.
currBucket = getHashIndex(elem);
for (bucketIter = buckets[currBucket]->begin(); bucketIter != buckets[currBucket]->end(); ++bucketIter) {
if (elem == *bucketIter) {
return true;
}
}
return false;
}
这是运营商的代码
template<class T>
SetT<T> SetT<T>::operator*(SetT& other)
{
SetT<T> result;
// Your code here
// This function should return the Intersection between "this" and otherSet.
// It should NOT change "this" or otherSet
for (int i = 0; i < numBuckets; i++) {
for (bucketIter = buckets[i]->begin(); bucketIter != buckets[i]->end(); ++bucketIter) {
T value = *bucketIter;
if (Contains(value) && other.Contains(value)) {
result.Add(value);
}
}
}
return result;
}
template<class T>
SetT<T> SetT<T>::operator=(const SetT& other)
{
if (other.numElems == 0) {
return SetT<T>();
}
else {
return other;
}
}
有谁知道是什么导致了这个错误?
谢谢。
编辑:这是教授的哈希函数
template<class T>
int SetT<T>::getHashIndex(const T& key)
{
// This is done... No touching!
unordered_map<int, T> mapper;
typename unordered_map<int, T>::hasher hashFunction = mapper.hash_function();
return static_cast<int>(hashFunction(key) % numBuckets);
}
解决方案
推荐阅读
- python - 如何在多行上将用户输入打印到 csv 文件?
- ios - 使用 Realm、Swift 保存不同的类别
- haskell - 重新定义haskell中的'all'函数
- javascript - 如何使用 jQuery 我可以找到其中没有/包含输入标签的表单?
- r - 多个模式匹配后替换数据表列中的多个值
- android - 具有 2 个实体的数据类混淆列
- python-3.x - ValueError: Input 0 is in compatible with layer average_pooling2d_1: expected ndim=4, found ndim=5
- javascript - JavaScript 函数异常
- javascript - 没有提供 'ref' 的参数。角 10
- android - 无法下载 versionedparcelable-1.1.0.aar (androidx.versionedparcelable:versionedparcelable:1.1.0)