#ifndef TOOLS_H #define TOOLS_H #include template //双向map工具类,实现key->value,value->key的映射 class BiDirectionalMap { public: // 插入键值对,确保双向唯一性 void insert(const Key& key, const Value& value) { // 删除旧键和旧值的关联(如果存在) if (m_keyToValue.contains(key)) { Value oldValue = m_keyToValue[key]; m_valueToKey.remove(oldValue); } if (m_valueToKey.contains(value)) { Key oldKey = m_valueToKey[value]; m_keyToValue.remove(oldKey); } // 插入新键值对 m_keyToValue[key] = value; m_valueToKey[value] = key; } // 根据键获取值 Value value(const Key& key) const { return m_keyToValue.value(key); } // 根据值获取键 Key key(const Value& value) const { return m_valueToKey.value(value); } // 检查键是否存在 bool containsKey(const Key& key) const { return m_keyToValue.contains(key); } // 检查值是否存在 bool containsValue(const Value& value) const { return m_valueToKey.contains(value); } // 通过键删除项 void removeByKey(const Key& key) { if (m_keyToValue.contains(key)) { Value value = m_keyToValue[key]; m_keyToValue.remove(key); m_valueToKey.remove(value); } } // 通过值删除项 void removeByValue(const Value& value) { if (m_valueToKey.contains(value)) { Key key = m_valueToKey[value]; m_valueToKey.remove(value); m_keyToValue.remove(key); } } private: QHash m_keyToValue; // 键 → 值 QHash m_valueToKey; // 值 → 键 }; #endif // DATABASE_H