QMap
是一個關聯數組,它將鍵(key)與值(value)相關聯。QMap
類提供了一系列方法來操作和查詢其中存儲的數據。下面是一些常見的QMap
方法及其示例代碼:
insert()
方法用于將鍵值對插入到QMap
中。如果鍵已經存在,那么它的值將被覆蓋。
cpp
QMap<int, QString> map;map.insert(1, "one");map.insert(2, "two");map.insert(3, "three");
value()
方法返回與指定鍵相關聯的值。如果鍵不存在,它將返回一個空的QVariant
。
cpp
QMap<int, QString> map;map.insert(1, "one");map.insert(2, "two");map.insert(3, "three");QString value = map.value(2); // 返回 "two"
key()
方法返回與指定值相關聯的鍵。如果值不存在,它將返回一個空的QVariant
。
cpp
QMap<int, QString> map;map.insert(1, "one");map.insert(2, "two");map.insert(3, "three");int key = map.key("two"); // 返回 2
count()
方法返回QMap
中鍵值對的數量。
cpp
QMap<int, QString> map;map.insert(1, "one");map.insert(2, "two");map.insert(3, "three");int count = map.count(); // 返回 3
contains()
方法檢查QMap
是否包含指定的鍵或值。
cpp
QMap<int, QString> map;map.insert(1, "one");map.insert(2, "two");map.insert(3, "three");bool containsKey = map.contains(2); // 返回 truebool containsValue = map.contains("two"); // 返回 true
begin()
和end()
方法返回QMap
的迭代器,可以用于遍歷其中的鍵值對。
cpp
QMap<int, QString> map;map.insert(1, "one");map.insert(2, "two");map.insert(3, "three");for (QMap<int, QString>::iterator it = map.begin(); it != map.end(); ++it) {int key = it.key(); // 返回當前鍵QString value = it.value(); // 返回當前值}
remove()
方法用于從QMap
中刪除指定的鍵值對。如果鍵不存在,該方法不會進行任何操作。
cpp
QMap<int, QString> map;map.insert(1, "one");map.insert(2, "two");map.insert(3, "three");map.remove(2); // 刪除鍵為 2 的鍵值對
clear()
方法用于清除QMap
中的所有鍵值對。
cpp
QMap<int, QString> map;map.insert(1, "one");map.insert(2, "two");map.insert(3, "three");map.clear(); // 清除所有鍵值對
這些只是QMap
類的一些常見方法,還有其他方法可以根據具體需求進行使用。請參考QMap
類的文檔以獲取更詳細的信息。