今天开始刷CC150,最前面的概念hashmap迷惑了
查了一下,在java中所有类型都有一个内建函数hashcode(), 这个函数能获取任何类型的hash值,帮助简历hash索引,所以任何类型都可以用java中的hashmap实现。 ps:equal函数
在C++中,找了半天貌似没有一个标准的回答,以下来自stackflow:
The STL has hash_map
, but the C++ Standard Library does not.
Due to a common misconception, you may think of the C++ Standard Library as "the STL", or of parts of your toolchains implementation of the C++ Standard Library as "an STL implementation". It is not.
It is also a great shame that both MSVC++ and GCC (which implement hash_map
as a compiler-specific extension), place it in the std
namespace, which is highly misleading. *sigh*
C++11 has introduced std::unordered_map
, which is not dissimilar.
意思是hashmap在C++中有,是STL但不是C++ 标准库,俩概念不一样,囧。
C++11推出unordered_map,用途比原来的hashmap要广,因为不单只支持一些简单的类型了。
但是貌似compare函数还得自己写。
实现方法伪代码:
//define a hash_map in cpp
//hash_map<int,string> hmap;//定义一个实例
//hmap.insert(pair<int,string>(10,"sfsfd"));//插入一个pair对象,
//hmap.insert(hash_map<int,string>::value_type(34,"sddsf"));//value_type就是pair类型的
hash_map<int, student> buildmap(student [])
{
hash_map<int,student> map = new hash_map<int, student>;
for(element in student)
{
map.insert(selement.getID(),element); //so there should be a inner method to get the ID which is the key you want to use
}
return(map);
}
//unordered_map similar to hash map, but is the new standard in C++11
总而言之,hashmap查找速度很快,一般是定值,map是logn