map & hashmap
c++里面也有map和hashmap,分别适用于不同场景。
详细介绍可以参考:
注意:虽然hashmap理论上查找在较好的情况下可以做到O(1),但是最好不要企图用hashmap取代数组,数组还是快与hashmap所以能用数组的直接用数组。
C++动态申请数组
int n = 10;
int* a = new int[n];
/*
* 其余代码
*/
delete[]a;
hashmap 示例代码:
1.
#include<unordered_map> //由于编译器报错,把hash_map换为了unordered_map
#include<iostream>
using namespace std;
int main(void)
{
unordered_map<unsigned int, unsigned int>hm;
//元素的插入:pair<iterator,bool>insert<const value_type &v>
//insert(inputiterator first,inputiterator last)
hm[0]=4;
hm[1]=5;
hm[2]=6;
hm[3]=7;
//元素的访问可以用,数组的方式也可以用迭代器的方式
unordered_map<unsigned int, unsigned int>::iterator i,iend,j;
iend=hm.end();
for(i=hm.begin();i!=iend;i++)
{
cout<<(*i).first<<" "
<<(*i).second<<endl;
}
cout<<"**************************************************"<<endl;
//元素的删除erase(),clear()
hm.erase(0);
for(i=hm.begin();i!=iend;i++)
{
cout<<(*i).first<<" "
<<(*i).second<<endl;
}
//元素的搜索
j=hm.find(1);
i=hm.find(2);
cout<<"水果:"<<(*i).first<<" "
<<"价钱:"<<(*i).second<<endl;
cout<<"**************************************************"<<endl;
if(j!=hm.end())
{
cout<<"hash_map容器的个数"<<hm.size()<<endl;
}
else
{
cout<<"哈希表的表长:"<<hm.bucket_count()<<endl;
}
return 0;
}
#include<unordered_map>
#include<iostream>
using namespace std;
unsigned int
int main(void)
{
unordered_map<const char*,float>hm;
//元素的插入:pair<iterator,bool>insert<const value_type &v>
//insert(inputiterator first,inputiterator last)
hm["apple"]=1.0f;
hm["pear"]=1.5f;
hm["orange"]=2.0f;
hm["banana"]=1.8f;
//元素的访问可以用,数组的方式也可以用迭代器的方式
unordered_map<const char*,float>::iterator i,iend,j;
iend=hm.end();
for(i=hm.begin();i!=iend;i++)
{
cout<<(*i).first<<" "
<<(*i).second<<endl;
}
cout<<"**************************************************"<<endl;
//元素的删除erase(),clear()
hm.erase("pear");
for(i=hm.begin();i!=iend;i++)
{
cout<<(*i).first<<" "
<<(*i).second<<endl;
}
//元素的搜索
j=hm.find("pear");
i=hm.find("apple");
cout<<"水果:"<<(*i).first<<" "
<<"价钱:"<<(*i).second<<endl;
cout<<"**************************************************"<<endl;
if(j!=hm.end())
{
cout<<"hash_map容器的个数"<<hm.size()<<endl;
}
else
{
cout<<"哈希表的表长:"<<hm.bucket_count()<<endl;
}
return 0;
}
std::map默认值
对于非基本类型, 例如class/struct等通过构函数设置默认值,对于int类型可以使用-std=c++17
,如下:
#include <iostream>
#include <vector>
#include <map>
int main()
{
std::map<std::string, std::optional<int>> myNullables;
std::cout << myNullables["empty-key"].value_or(-1) << std::endl;
return 0;
}
/*
output:
-1
*/