Qt中的QMap介紹與使用,在壇子裡逛了一圈,發現在使用QMap中,出現過很多的問題,Map是一個很有用的資料結構。它以“鍵-值”的形式儲存資料。在使用的時候,通過提供字元标示(鍵)即可得到想要的資料。這個“資料”即可以是一個字元串,也可以是任意對象,當然也包括自己定義的類對象。說明:map是以值傳遞的形式儲存資料的。
1. 基本應用
下面以“鍵-值”都是QString的例子說明QMap的基本使用方法。更詳細的說明,請檢視《Qt幫助手冊》或其他資源。
[cpp] view plain copy
- #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(),顯示結果:
[cpp] view plain copy
- 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》,更詳細的說明參考之):
以注釋形式說明
[cpp] view plain copy
- #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的知識