QMap使用

版權聲明:若無來源註明, Techie亮博客文章均爲原創。 轉載請以連接形式標明本文標題和地址:
本文標題:QMap使用     本文地址: https://www.techieliang.com/2017/12/537/

1. 簡單範例

QMap與std::map相同,會自動根據key(第一項)進行升序排列html

  1. QMap<QString,int> m_map;
  2. m_map["a"] = 10;//插入方式1
  3. m_map["as"] = 13;
  4. m_map.insert("b",22);//插入方式2
  5. m_map.insert("ba",23);
  6. auto find_index = m_map.find("as");//搜索
  7. if(find_index!=m_map.end()) {//返回爲end代表未搜索到
  8. qDebug()<<find_index.key()<<find_index.value();
  9. }
  10. qDebug()<<m_map.value("a");//直接搜索,根據值key找值
  11. qDebug()<<m_map.value("aa");//沒這項
  12. qDebug()<<m_map.key(13);//根據值找key
  13. qDebug()<<m_map.key(14);//沒這項

返回結果:app

  1. "as" 13
  2. 10
  3. 0
  4. "as"
  5. ""

相關幫助文檔請見官網函數

erase刪除某項,因爲map的key具備惟一性,能夠經過m_map[XX]=YY;修改已有項的值,若此項並不存在則會建立新的。post

2. 其餘

2.1. value/key方法返回值

value若查找不到目標會返回默認值,對於默認值得解釋:this

Returns a list containing all the values in the map, in ascending order of their keys. If a key is associated with multiple values, all of its values will be in the list, and not just the most recently inserted one.spa

若是沒有主動設置默認值,返回Qt默認值,此值在文檔的容器介紹有說明code

The documentation of certain container class functions refer to default-constructed values; for example, QVector automatically initializes its items with default-constructed values, and QMap::value() returns a default-constructed value if the specified key isn’t in the map. For most value types, this simply means that a value is created using the default constructor (e.g. an empty string for QString). But for primitive types like int and double, as well as for pointer types, the C++ language doesn’t specify any initialization; in those cases, Qt’s containers automatically initialize the value to 0.htm

key方法若找不到相應key,一樣返回默認值。ip

2.2. QMap與std::map

QMap使用Iterator.key(),和Iterator.value()方法獲取第一個或第二個元素的值。ci

而std::map使用Iterator->first(), Iterator->second()來獲取第一個或第二個元素的值

2.3. std::map<Key, T> QMap::toStdMap() const

QMap實現了與std::map相互轉換,toStdMap轉到std,使用QMap的構造函數從std::map轉到QMap

  1. QMap(std::initializer_list<std::pair<Key, T> > list)
  2. QMap(const QMap<Key, T> &other)
  3. QMap(QMap<Key, T> &&other)
  4. QMap(const std::map<Key, T> &other)//能夠導入std::map

 

轉載請以連接形式標明本文標題和地址: Techie亮博客 » QMap使用
相關文章
相關標籤/搜索