Qt(十)QHash


是否包含 contains
元素个数 count
清空 clear
判断key的位置 equal_range
判断是否为空 empty
查找元素 find
键列表 keys
值列表 values
删除指定key元素 take

常用方法

//是否包含key
bool contains(const Key &key) const

//返回与键 key 关联的项目数。
QHash::size_type count(const Key &key) const

// 清空
void clear()

// 判空
bool empty() const

// 返回一对迭代器,它们界定了存储在 key 下的值 [first, second) 的范围。
QPair<QHash::iterator, QHash::iterator> equal_range(const Key &key)

//查找指定的key元素
QHash::iterator find(const Key &key)

//获取头
T &first()

//添加
void insert(const QHash<Key, T> &map)

//key列表
QList<Key> keys() const

//删除指定key元素
T take(const Key &key)

//值列表
QList<T> values() const

QHash 初始化 与 添加

#include <QHash>
#include <QDebug>

QHash<quint32, bool> temp0 {
    
    {
    
    1,false},{
    
    2, true}};
QHash<QString, QString> temp1 {
    
    {
    
    "a","b"},{
    
    "c","d"}};

QHash<QString, QString> map;
map.insert("3name", "leo");
map.insert("1age", "18");
map.insert("2like", "eat");
map.insert("4sex", "man");

QHash<quint32,QString> mapNames;
mapNames.insert(1,"张三");
qDebug()<<mapNames;
mapNames.insert(1,"张三");
qDebug()<<mapNames;
mapNames.insert(2,"张四");
mapNames.insert(3,"张五");
mapNames.insert(4,"张六");
mapNames[5] = "张七";
qDebug()<<mapNames;

QHash遍历–查找–删除

void init_info()
{
    
    

    QHash<quint32,QString> mapNames = {
    
    {
    
    2,"张2"},{
    
    1,"张1"},{
    
    3,"张3"},{
    
    0,"张0"}};

    for(auto it:mapNames){
    
    
        qDebug()<<it;
    }

    for(auto it =mapNames.begin();it!=mapNames.end();it++){
    
    
        qDebug()<<*it;
    }

    for(int i = 0;i<mapNames.size();i++){
    
    
        qDebug()<<mapNames[i];
    }

    auto it = mapNames.find(1);
    //直接访问 mapNames[1]


    // 单个擦除, 清空
    auto _it = mapNames.begin();
    mapNames.erase(_it);
    qDebug()<<mapNames;
    mapNames.clear();
}

QHash 值嵌套

struct Person
 {
    
    
      QString strName;
      QString  strId;
      quint16  uiAge;
};

void print_info(){
    
    
    QHash<QString, Person> em;                //自定义一个map类型,值为EmployeeMap对象
    em["john"] =  Person{
    
    "john", "111", 12};  //向map里插入键-值
    em["lilei"] = Person{
    
    "lilei", "222", 13};
    em["tom"] =   Person{
    
    "tom", "Jones", 14};

    //批量打印, 修改 value中的值
    for(auto &it: em){
    
    
        if (it.strName == "tom")
            it.uiAge = 500;
    }
}

拓展阅读
QMap和QHash

猜你喜欢

转载自blog.csdn.net/wsp_1138886114/article/details/123480932