容器类之 unordered_map

来源:互联网 发布:linux版本的abaqus6.16 编辑:程序博客网 时间:2024/05/06 09:24

该容器的特点

  1. 存放数据的方式:key = value,通过key进行检索。
  2. 存放数据时无序的。
  3. 检索的速度比map类快。
  4. 重载了[ ]运算符。
  5. iterator可以访问keyvalue

    unordered_map<int, bool> m = {        { 5, true },        { 6, true }    };unordered_map<int, bool>::iterator it = m.begin();int key = it->first;bool b = it->second;

与检索相关的成员函数

  1. operator[key]

    查找成功:返回value引用(reference)

    查找失败:在map后面插入一个新的元素,key为当前查找的值,value在未赋值的情况下是为空的。

    // unordered_map::operator[]#include <iostream>#include <string>#include <unordered_map>using namespace std;int main (){  unordered_map<string,string> mymap;  mymap["Bakery"]="Barbara";    // not found, new element inserted  mymap["Seafood"]="Lisa";      // not found, new element inserted  mymap["Produce"]="John";      // not found, new element inserted  string name = mumap["XXXXX"]; // not found, the new element inserted, but the value is NULL.  for (auto& x: mymap) {    cout << x.first << ": " << x.second << endl;  }  return 0;}output result:    Bakery: Barbara    Seafood: Lisa    Produce: John    XXXXX: 

    auto& x : mymap:使用智能指针进行遍历。

  2. find(key)

    查找成功:返回一个iterator,指向该元素。

    查找失败:返回一个iterator,指向map.end()

  3. at(key)

    查找成功:返回引用。

    查找失败:抛出out_of_range#include <stdexcept>)异常。

    #include <iostream>       // std::cerr#include <stdexcept>      // std::out_of_range#include <vector>         // std::vectorint main (void) {    std::unordered_map<int, bool> m = {        { 5, true },        { 6, true }    };    int i = 7;    try {        m.at(i);    //find the value of which the key is 7.    } catch (const std::out_of_range& oor) {        std::cerr << "Out of Range error: " << oor.what() << '\n';        std::cerr << "Out of Range error: " << "the key " << i << " not found." << '\n';    }    return 0;}

    orr.what():打印错误流中的信息。

0 0