c++11 - C++ Iterator with hasNext and Next -
i new c++ world , need help. problem try implement structure hash pair array, there key , data. in structure have nested structure iterator methods hasnext , next. because can not see array (this array in parent) nested structure need pass through constructor, there error ": cannot convert from...", problem pass _array in method getiterator. code below. me? thanks
#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 collision records par* _overflow; par(t t, u u) { _first = t; _second = u; _overflow = nullptr; } }; hashparovepole() {} // static array save data par* _array[size]; // add record hash table void add(t t, u u) { // calculating of index par* prvek; int idx = hashfunction(t) % size; // element saved in _array[idx], if free, else //saved list (->_overflow) prvek = new par(t, u); if (_array[idx] == nullptr) { _array[idx] = prvek; } else { prvek->_overflow = _array[idx]; } _array[idx] = prvek; } // data 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 walking 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); } };
as far see, problem in line:
par* _array[size];
here declare array of size size
of pointers par
structures, not want.
later try pass array constructor iterator(par * _array)
, accepts pointer par
structure, impossible.
i fix code in following way:
par _array[size]; // instead of par* _array[size] // need array of structures instead of array of pointers ... par* index; // instead of par* index[size] // here looks index pointer current element ... pompar = index; // instead of pompar = index[0]; // pointer node, while index[0] value
also, consider using std::vector
instead of raw pointers. handle memory management issues you.
Comments
Post a Comment