QT QMap介紹與使用
Qt中的QMap介紹與使用,在壇子里逛了一圈,發(fā)現(xiàn)在使用QMap中,出現(xiàn)過很多的問題,Map是一個很有用的數(shù)據(jù)結(jié)構(gòu)。它以“鍵-值”的形式保存數(shù)據(jù)。在使用的時候,通過提供字符標(biāo)示(鍵)即可得到想要的數(shù)據(jù)。這個“數(shù)據(jù)”即可以是一個字符串,也可以是任意對象,當(dāng)然也包括自己定義的類對象。說明:map是以值傳遞的形式保存數(shù)據(jù)的。
1. 基本應(yīng)用
下面以“鍵-值”都是QString的例子說明QMap的基本使用方法。更詳細(xì)的說明,請查看《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里是否已經(jīng)包含某“鍵-值”
- 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里對應(yīng)的值
- }
- cout<< endl;
- qDebug("size of this map is : %d", m_map.count()); //獲取map包含的總數(shù)
- 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對象
- };
調(diào)用類函數(shù)showMap(),顯示結(jié)果:
- map[333] , value is : ccc
- find 111 , value is : aaa
- size of this map is : 3
- 111: aaa
- 222: bbb
- 333: ccc
2. 對象的使用
map當(dāng)中還可以保存類對象、自己定義類對象,例子如下(摘自QT幫助文檔《Qt Assistant》,更詳細(xì)的說明參考之):
以注釋形式說明
- #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值的內(nèi)容,因為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
小結(jié):QMap介紹與使用的內(nèi)容介紹完了,基本是在講QMap的使用,那么通過本文希望你能了解更多關(guān)于QMap的知識。