Qhash简介
- Qhash是无序的,插入的顺序和输出的顺序并不相同。
void Widget::on_pushButton_clicked()
{
QHash<int, QString> m_hash;
m_hash.insert(1, "tanglin");
m_hash.insert(2, "renyong");
m_hash.insert(3, "wenqiang");
m_hash.insert(4, "laowang");
foreach (QString value, m_hash) {
qDebug() << value;
}
}
//第一次调试输出
"wenqiang"
"renyong"
"tanglin"
"laowang"
//第二次调试输出
"tanglin"
"laowang"
"wenqiang"
"renyong"
2.Qhash如果插入相同的 key,则后面的 key,value 将覆盖前一次的 key,value
void Widget::on_pushButton_2_clicked()
{
QHash<int, QString> m_hash;
m_hash.insert(4, "laowang");
m_hash.insert(4, "libai");
qDebug() << m_hash.value(4);
}
//输出
"libai"
- 自定义数据类型
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
private slots:
void on_pushButton_clicked();
void on_pushButton_2_clicked();
void on_pushButton_3_clicked();
void on_pushButton_4_clicked();
private:
Ui::Widget *ui;
};
struct myDate
{
private:
int age;
QString name;
public:
inline bool operator ==(const myDate &other) const
{
return (this->age == other.age && this->name == other.name);
}
myDate(int age, QString name)
{
this->age = age;
this->name = name;
}
myDate()
{
this->age = 20;
this->name = "libia";
}
};
#endif // WIDGET_H
#include "widget.h"
#include "ui_widget.h"
#include <QMap>
#include <QHash>
#include <QString>
#include <QDebug>
#include <QList>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
//定义一个map容器
QMap<int, QString> map;
//向map容器里面插入数据
map.insert(1, "tanglin");
map.insert(2, "renyong");
map.insert(3, "yongxiang");
//读取数据
QString temp;
temp = map.value(1);
qDebug() << temp;
//返回key和value的列表
QList<int> keylist = map.keys();
foreach (int key, keylist) {
qDebug() << key;
}
QList<QString> valueList = map.values();
// foreach (QString value, valueList) {
// qDebug() << value;
// }
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_pushButton_clicked()
{
QHash<int, QString> m_hash;
m_hash.insert(1, "tanglin");
m_hash.insert(2, "renyong");
m_hash.insert(3, "wenqiang");
m_hash.insert(4, "laowang");
foreach (QString value, m_hash) {
qDebug() << value;
}
}
void Widget::on_pushButton_2_clicked()
{
QHash<int, QString> m_hash;
m_hash.insert(4, "laowang");
m_hash.insert(4, "libai");
qDebug() << m_hash.value(4);
}
//查找
void Widget::on_pushButton_3_clicked()
{
QHash<int, QString> m_hash;
m_hash.insert(1, "tanglin");
m_hash.insert(2, "renyong");
m_hash.insert(3, "wenqiang");
m_hash.insert(4, "laowang");
auto it = m_hash.find(3);
if(it != m_hash.end())
{
qDebug() << it.value();
}
}
//自定义数据类型
void Widget::on_pushButton_4_clicked()
{
QHash<myDate, QString> m_hash;
m_hash.insert(myDate(), "good");
m_hash.insert(myDate(11, "nihao"), "bad");
qDebug() << m_hash.value(myDate());
}
uint qHash(const myDate &selt, uint seed)
{
return 100^seed;
}