QMap使用


博客地址已更改,文章數量較多不便批量修改,若想訪問源文請到 coologic博客 查閱,網址:www.coologic.cn

如本文記錄地址為 techieliang.com/A/B/C/ 請改為 www.coologic.cn/A/B/C/ 即可查閱

 

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

1. 簡單范例

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

  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);//沒這項

返回結果:

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

相關幫助文檔請見官網

erase刪除某項,由於map的key具有唯一性,可以通過m_map[XX]=YY;修改已有項的值,若此項並不存在則會創建新的。

2. 其他

2.1. value/key方法返回值

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

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.

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

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.

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

2.2. QMap與std::map

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

而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使用


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM