C++ unordered_map

unordered_map与hash_map对比:

  1. unordered_map原来属于boost分支和std::tr1中,而hash_map属于非标准容器。
  2. unordered_map感觉速度和hash_map差不多,但是支持string做key,也可以使用复杂的对象作为key。

HashMap的定义

整形定义

#include <iostream>
#include <unordered_map>
using namespace std;

int main(){
    unordered_map <int, int> inthash;
    inthash[1] = 123;
    inthash[2] = 456;
    int val1 = inthash[1];
    int val2 = inthash[2];
    cout << val1 << endl;
    cout << val2 << endl;
}

字符型定义

#include <iostream>
#include <unordered_map>
using namespace std;

int main(){
    unordered_map <string, int> strhash;
    strhash["a"] = 123;
    strhash["b"] = 456;
    int val1 = strhash["a"];
    int val2 = strhash["b"];
    cout << val1 << endl;
    cout << val2 << endl;
}

HashMap的遍历

#include <iostream>
#include <unordered_map>
using namespace std;

int main(){
    unordered_map<int, int> intHash;
    intHash[1] = 123;
    intHash[2] = 456;
    intHash[3] = 789;
    for (auto it = intHash.begin(); it != intHash.end(); ++it)
        cout << " " << it->first << ":" << it->second << endl;
}

HashMap的查找

#include <iostream>
#include <unordered_map>
using namespace std;

int main(){
    unordered_map<int, string> strHash;
    strHash[12] = "123";
    strHash[25] = "456";
    strHash[39] = "789";
    unordered_map<int, string>::iterator it = strHash.begin();
    it = strHash.find(25);
    if(it != strHash.end()){
        cout << it->second << endl;
    }else
    {
        cout << "not find" << endl;
    }
}

显示HashMap的大小

#include <iostream>
#include <unordered_map>
using namespace std;

int main(){
    unordered_map<string, string> strHash;
    strHash["a"] = "123";
    strHash["b"] = "456";
    strHash["c"] = "789";
    cout << strHash.size() << endl;
}

判断HashMap是否为空

#include <iostream>
#include <unordered_map>
using namespace std;

int main(){
    unordered_map<const char*, string> strHash;
    strHash["a"] = "123";
    strHash["b"] = "456";
    strHash["c"] = "789";
    cout << strHash.empty() << endl;
}

删除HashMap中的元素

#include <iostream>
#include <unordered_map>
using namespace std;

int main(){
    unordered_map<string, string> strHash;
    strHash["a"] = "123";
    strHash["b"] = "456";
    strHash["c"] = "789";

    strHash.erase("a");

    unordered_map<string, string>::iterator it = strHash.begin();
    while (it != strHash.end()){
        cout<< it->first <<"\t" << it++->second <<endl;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小鹏AI

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值