Qt中的QMap介紹與使用,在罈子裏逛了一圈,發現在使用QMap中,出現過很多的問題,Map是一個很有用的數據結構。它以“鍵-值”的形式保存數據。在使用的時候,通過提供字符標示(鍵)即可得到想要的數據。這個“數據”即可以是一個字符串,也可以是任意對象,當然也包括自己定義的類對象。說明:map是以值傳遞的形式保存數據的。
1. 基本應用
下面以“鍵-值”都是QString的例子說明QMap的基本使用方法。更詳細的說明,請查看《Qt幫助手冊》或其他資源。
- #include <qmap.h>
- #include <iostream>
- using namespace std;
- class MapTest
- {
- public:
- void showMap()
- {
- if(!m_map.isEmpty()) return; //判斷map是否爲空
- m_map.insert("111", "aaa"); //向map裏添加一對“鍵-值”
- if(!m_map.contains("222")) //判斷map裏是否已經包含某“鍵-值”
- m_map.insert("222", "bbb");
- m_map["333"] = "ccc"; //另一種添加的方式
- qDebug("map[333] , value is : " + m_map["333"]); //這種方式既可以用於添加,也可以用於獲取,但是你必須知道它確實存在
- if(m_map.contains("111")){
- QMap<QString,QString>::iterator it = m_map.find("111"); //找到特定的“鍵-值”對
- qDebug("find 111 , value is : " + it.data()); //獲取map裏對應的值
- }
- cout<< endl;
- qDebug("size of this map is : %d", m_map.count()); //獲取map包含的總數
- cout<< endl;
- QMap<QString,QString>::iterator it; //遍歷map
- for ( it = m_map.begin(); it != m_map.end(); ++it ) {
- qDebug( "%s: %s", it.key().ascii(), it.data().ascii()); //用key()和data()分別獲取“鍵”和“值”
- }
- m_map.clear(); //清空map
- }
- private:
- QMap<QString,QString> m_map; //定義一個QMap對象
- };
調用類函數showMap(),顯示結果:
- map[333] , value is : ccc
- find 111 , value is : aaa
- size of this map is : 3
- 111: aaa
- 222: bbb
- 333: ccc
2. 對象的使用
map當中還可以保存類對象、自己定義類對象,例子如下(摘自QT幫助文檔《Qt Assistant》,更詳細的說明參考之):
以註釋形式說明
- #include <qstring.h>
- #include <qmap.h>
- #include <qstring.h>
- //自定義一個Employee類,包含fn、sn、sal屬性
- class Employee
- {
- public:
- Employee(): sn(0) {}
- Employee( const QString& forename, const QString& surname, int salary )
- : fn(forename), sn(surname), sal(salary)
- { }
- QString forename() const { return fn; }
- QString surname() const { return sn; }
- int salary() const { return sal; }
- void setSalary( int salary ) { sal = salary; }
- private:
- QString fn;
- QString sn;
- int sal;
- };
- int main(int argc, char **argv)
- {
- QApplication app( argc, argv );
- typedef QMap<QString, Employee> EmployeeMap; //自定義一個map類型,值爲EmployeeMap對象
- EmployeeMap map;
- map["JD001"] = Employee("John", "Doe", 50000); //向map裏插入鍵-值
- map["JW002"] = Employee("Jane", "Williams", 80000);
- map["TJ001"] = Employee("Tom", "Jones", 60000);
- Employee sasha( "Sasha", "Hind", 50000 );
- map["SH001"] = sasha;
- sasha.setSalary( 40000 ); //修改map值的內容,因爲map採用值傳遞,所以無效
- //批量打印
- EmployeeMap::Iterator it;
- for ( it = map.begin(); it != map.end(); ++it ) {
- printf( "%s: %s, %s earns %d\n",
- it.key().latin1(),
- it.data().surname().latin1(),
- it.data().forename().latin1(),
- it.data().salary() );
- }
- return 0;
- }
- Program output:
- JD001: Doe, John earns 50000
- JW002: Williams, Jane earns 80000
- SH001: Hind, Sasha earns 50000
- TJ001: Jones, Tom earns 60000
小結:QMap介紹與使用的內容介紹完了,基本是在講QMap的使用,那麼通過本文希望你能瞭解更多關於QMap的知識。