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使用
相关文章
相关标签/搜索