注意这是作业,但我们被允许并鼓励寻求帮助,因为我们的单一教授没有时间回应所有学生。如果因为这个问题的功课性质而不愿意帮忙,请不要回复,而应该寻求帮助。我不希望我的作业为我完成。我只是想帮助理解我的错误所在。所有帮助表示赞赏!C++ 11基于阵列的散列:自动不循环
我正在处理基于数组的哈希表。我在散列中有一些值,我想检查散列中所有元素长度的总和。散列中的元素是字符串。
我使用的后续代码通过在散列值的每个成员进行迭代...
for (auto iter : myHash) {
//count up the length of all the strings
countOfItems += iter.length();
cout << iter << " ";
}
的问题是,在代码永远不会循环,一次也没有。它从来没有击中countOfItems + = iter.length();
我调试了这个问题,并尽我所能,但仍然失去了我的迭代器。我将在这里这些张贴在这里...迭代器
template <typename KEY, typename VALUE>
arrayHashIterator<KEY, VALUE> arrayHashTable<KEY, VALUE>::begin() const {
arrayHashIterator<KEY, VALUE> temp;
temp.keyArray = this->keyArray;
temp.valueArray = this->valueArray;
temp.statusArray = this->statusArray;
temp.index = 0;
temp.arraySize = this->arraySize;
temp.offTheRightEdge = false;
if (temp.statusArray[0] != 1) {
//Go search for the first index that contains useful data
++temp;
}
return temp;
}
当代码到达重载++运算符它进入这个其他类...
template <typename KEY, typename VALUE>
arrayHashIterator<KEY, VALUE> arrayHashIterator<KEY, VALUE>::operator++() {
for(index; index < arraySize; index++){
if(statusArray[index] == 1)
{
offTheRightEdge = false;
return *this;
}
}
offTheRightEdge = true;
return *this;
}
现在我调试和步该代码正确地获取重载的++运算符,然后找到存储值的第一个索引,然后将该arrayHashIterator对象返回到begin(),然后将其返回。我希望它会有东西进入(Auto iter:Hash)循环,但它没有。
我要针对arrayHashIterator类重载运算符*如下所述...
template <typename KEY, typename VALUE>
VALUE& arrayHashIterator<KEY, VALUE>::operator*() const{
if(offTheRightEdge == true){
throw Error();
}
return valueArray[index];
}
我几乎可以肯定我已经进入元素融入到我的散列正确的,因为如果我打开我的数组值,以及作为调试器中的键和状态,我发现所有信息都以正确的形式出现在正确的位置。
我只是为了(auto iter:hash)无法循环而感到茫然。我确实相信这个问题出现在我的重载++或重载操作符中,但我不能确定。
关于这个问题的第二双眼睛将不胜感激。我不想要一些即时回答的代码片段,我只是感谢一些帮助找到错误,以及我可以如何解决它!
编辑:有很多更多的代码散列表和每个用例的检查,但我想发布特定部分到我的问题是。我可以根据要求提供代码。
编辑:这是我为我的end()方法以及我重载=操作...
更新:!重载!=
template <typename KEY, typename VALUE>
bool arrayHashIterator<KEY, VALUE>::operator!=(const arrayHashIterator<KEY, VALUE>& right) const {
//TODO: see if the "this" iterator and the right iterator are not equal.
//To do this, check both iterators' index values and offTheRightEdge values
if(this->offTheRightEdge != right.offTheRightEdge || this->index != right.index) {
return true;
} else {
return false;
}
}
末()
template <typename KEY, typename VALUE>
arrayHashIterator<KEY, VALUE> arrayHashTable<KEY, VALUE>::end() const {
arrayHashIterator<KEY, VALUE> temp;
temp.keyArray = this->keyArray;
temp.valueArray = this->valueArray;
temp.statusArray = this->statusArray;
temp.index = this->arraySize;
temp.arraySize = this->arraySize;
temp.offTheRightEdge = true;
return temp;
}
'end()'怎么样? 'arrayHashIterator'的比较'!='怎么样? –
@CaptainGiraffe,我现在已经将它们添加到主帖子中。 End基本上设置了终点。 temp.index被设置为数组大小,offTheRightEdge被设置为true。 !=运算符会检查调用对象的索引和offTheRightEdge值以及传入对象/两个比较对象是true还是false。 –