1. 基本应用
下面以“键-值”都是QString的例子说明QMap的基本使用方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| #include <qmap.h> #include <iostream>
using namespace std;
class MapTest { public: void showMap() { if(!m_map.isEmpty()) return; { m_map.insert(“111″, “aaa”); }
if(!m_map.contains(“222″)) { 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()); }
cout<< endl; qDebug(“size of this map is : %d”, m_map.count()); cout<< endl;
QMap<QString,QString>::iterator it; for ( it = m_map.begin(); it != m_map.end(); ++it ) { qDebug( “%s: %s”, it.key().ascii(), it.data().ascii()); } m_map.clear(); }
private: QMap<QString,QString> m_map; };
|
调用类函数showMap(),显示结果:
1 2 3 4 5 6 7 8
| 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》,更详细的说明参考之):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| #include <qstring.h> #include <qmap.h> #include <qstring.h>
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: int sal; QString fn; QString sn; };
int main(int argc, char **argv) { QApplication app( argc, argv );
typedef QMap<QString, Employee> EmployeeMap; EmployeeMap map;
map["JD001"] = Employee(“John”, “Doe”, 50000); map["JW002"] = Employee(“Jane”, “Williams”, 80000); map["TJ001"] = Employee(“Tom”, “Jones”, 60000);
Employee sasha( “Sasha”, “Hind”, 50000 ); map["SH001"] = sasha;
sasha.setSalary( 40000 );
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; }
|
输出结果:
1 2 3 4
| JD001: Doe, John earns 50000 JW002: Williams, Jane earns 80000 SH001: Hind, Sasha earns 50000 TJ001: Jones, Tom earns 60000
|