C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了C++ unordered_map大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

是一种特殊的map,查询值的复杂度为O(1),但是map查询值的复杂度为O(log N)

有的编译器使用时要加入下面的头文件

#if(__cplusplus == 201103L)
#include <unordered_map>
#include <unordered_set>
#else
#include <tr1/unordered_map>
#include <tr1/unordered_set>
namespace std
{
    using std::tr1::unordered_map;
    using std::tr1::unordered_set;
}
#endif

下面看几个函数

#include <bits/stdc++.h>
#if(__cplusplus == 201103L)
#include <unordered_map>
#include <unordered_set>
#else
#include <tr1/unordered_map>
#include <tr1/unordered_set>
namespace std
{
    using std::tr1::unordered_map;
    using std::tr1::unordered_set;
}
#endif
using namespace std;
const int maxn = 1e5 + 100;
unordered_map<int,int> fa;
int main() {
    fa[1]=2;
    fa[2]=3;
    fa[3]=4;
    fa[4]=0;
    //count函数 查询键值是否有值  返回0或者1 
    cout<<fa.count(5)<<endl;//0
    cout<<fa.count(4)<<endl;//1
    cout<<fa.count(3)<<endl;//1
    if(fa.find(1)==fa.end()) cout<<"不存在"<<endl;//存在 
    else cout<<"存在"<<endl;
    if(fa.find(4)==fa.end()) cout<<"不存在"<<endl;//存在 
    else cout<<"存在"<<endl;  
    if(fa.find(5)==fa.end()) cout<<"不存在"<<endl;//不存在 
    else cout<<"存在"<<endl; 
    
    //遍历fa
    unordered_map<int,int>::iterator it;
    for(it=fa.begin();it!=fa.end();)
    {
        cout<<it->first<<" "<<it->second<<endl;
        ++it;
     } 
     cout<<endl<<endl;
     //移除某个键值为奇数的元素 
     for(it=fa.begin();it!=fa.end();)
    {
        if(it->first%2==1) it=fa.erase(it); //删除之后指向下一个 
        else ++it;
     } 
     for(it=fa.begin();it!=fa.end();)
    {
        cout<<it->first<<" "<<it->second<<endl;
        ++it;
     } 
    return 0;
}

大佬总结

以上是大佬教程为你收集整理的C++ unordered_map全部内容,希望文章能够帮你解决C++ unordered_map所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。