C++ 带有 hasNext 和 Next 的迭代器



我是C++世界的新手,我需要帮助。我的问题是我尝试实现我的结构哈希对数组,有键和数据。在这个结构中,我有嵌套的结构迭代器,方法有下一个和下一个。因为我无法从嵌套结构中看到我的数组(这个数组在父数组中),我需要通过构造函数传递它,但存在错误":无法从...转换",问题在于方法getIterator中的传递_array。代码如下。你能帮我吗?谢谢

#pragma once
template<typename T, typename U, int Size, int(*HashFunction)(T)>
struct HashPairPole {
// Pair - key - data
struct Par {
// key
T _first;
// data
U _second;
// list for collision records
Par* _overflow;
Par(T t, U u) {
_first = t;
_second = u;
_overflow = nullptr;
}
};

HashParovePole() {}
// Static array for save data
Par* _array[Size];
// Add record into hash table
void add(T t, U u) {
// calculating of index     
Par* prvek;
int idx = HashFunction(t) % Size;
// Element will be saved in _array[idx], if it is free, else will be
//saved to list (->_overflow)
prvek = new Par(t, u);
if (_array[idx] == nullptr) {
_array[idx] = prvek;
}
else {
prvek->_overflow = _array[idx];
}
_array[idx] = prvek;
}
// Get data from hash tabule
U& get(T t) {
int idx = HashFunction(t) % Size;
Par * prvni = _array[idx];
while (prvni->_overflow != nullptr) {
if (prvni->_first == t) {
return prvni->_second;
}
prvni = prvni->_overflow;
}
}
U& operator[](T t) {
return get(t);
}
U operator[](T t) const {
const U temp = get(t);
return temp;
}
// Iterator for walking all hash table
struct iterator {
Par* index[Size];
Par* pomPar;
int temp = 0;
iterator(Par * _array) {
index = _array;
pomPar = index[0];
}
bool hasNext()const {
return pomPar != nullptr;
}

std::pair<T, U> next() {
std::pair<T, U> data;
if (hasNext()) {
data.first = pomPar->_first;
data.second = pomPar->_second;
pomPar = pomPar->_overflow;
}
temp++;
pomPar = index[temp];
return data;
}
};
// Vytvori iterator
iterator getIterator() {
return iterator(_array);
}
};

据我所知,问题出在这一行:

Par* _array[Size];

在这里,您声明了一个大小数组Size指向Par结构的指针,这可能不是您想要的。

稍后您尝试将此数组传递给构造函数iterator(Par * _array),它接受指向Par结构的指针,这是不可能的。

我将通过以下方式修复此代码:

Par _array[Size]; // Instead of Par* _array[Size]
// You need an array of structures instead of array of pointers
...
Par* index; // Instead of Par* index[Size]
// Here looks like index is a pointer to a current element
...
pomPar = index; // Instead of pomPar = index[0];
// This is a pointer to the node, while index[0] is its value

此外,请考虑使用std::vector而不是原始指针。它将为您处理内存管理问题。

最新更新