PDA

View Full Version : QHash <int, class*>



ArkKup
19th December 2011, 11:34
Hi,

I started playing with QHash, but I cant make hashPersons function to enumerate all keys and value since its crashing and I don't know why, please help :(



class Person
{

public:
Person( QString name, QString number );

QString m_name, m_number;
};

Person::Person( QString name, QString number ) : m_name( name ), m_number( number ) {}

void hashPersons()
{

QHash<int, Person*> hash;
hash[12] = new Person( "Anders", "8447070" );
hash[20] = new Person( "Micke", "7728433" );

QHashIterator<int, Person*> i(hash);

while (i.hasNext()) {

qDebug()<<i.key();
Person *per = i.value();

qDebug()<< "Name: " << per->m_name << "Number: "<<per->m_number;
i.next();
}
hash.clear();
}

also if I call hash.clear() at the end do I need to delete the value first or clear() will take care of it ?

stampede
19th December 2011, 12:14
You need to call i.next() before taking the value with i.value() (btw. its in the first example in QHashIterator documentation):


while (i.hasNext()) {
i.next();
qDebug()<<i.key();
Person *per = i.value();
if( per ){ // better check before dereferencing a pointer
qDebug()<< "Name: " << per->m_name << "Number: "<<per->m_number;
}
}


also if I call hash.clear() at the end do I need to delete the value first or clear() will take care of it ?
Yes you need to delete allocated values yourself, QHash does not know what kind of data you keep inside it.

Lykurg
19th December 2011, 12:45
hash.clear(): See qDeleteAll() for convenience.