David的测试技术空间,收藏好文档和分享我的技术理解。5年的数通产品测试和安全产品测试经验,3年Web产品测试和多年测试管理和测试工具开发经验。目前关注性能分析调优、Jmeter和TestNG+WebDriver+Hamcrest的培训推广。Welcome沟通交流,请留言或者发邮件到daviwang_2004 at soguo.com。

hash_map实例

上一篇 / 下一篇  2008-05-20 10:26:06 / 个人分类:旧资料

http://www.codeguru.com/forum/showthread.php?t=315286

#include
<string>
#include<hash_map>
#include<iostream>

// The following class defines a hash function for strings
classstringhasher :publicstdext::hash_compare <std::string>
{
public:
/**
* Required by
* Inspired by the java.lang.String.hashCode() algorithm
* (it's easy to understand, and somewhat processor cache-friendly)
* @param The string to be hashed
* @return The hash value of s
*/

size_toperator() (conststd::string& s)const
{
size_t h = 0;
std::string::const_iterator p, p_end;
for(p = s.begin(), p_end = s.end(); p != p_end; ++p)
{
h = 31 * h + (*p);
}
returnh;
}

/**
*
* @param s1 The first string
* @param s2 The second string
* @return true if the first string comes before the second in lexicographical order
*/

booloperator() (conststd::string& s1,conststd::string& s2)const
{
returns1 < s2;
}
};

typedefstdext::hash_map<std::string, std::string, stringhasher> HASH_S_S;

/**
* Compile this program with "cl -GX hash_sample.cpp"
* if using MSVC++ 7.1 (Visual Studio .NET 2003)
*/

intmain(intargc,char*argv[])
{
HASH_S_S hm;
HASH_S_S::iterator it;

//-- Inserting the names of months in a hash map
//-- key = names of the months in Portuguese
//-- value = names of the months in English
hm[std::string("janeiro")] = std::string("January");
hm[std::string("fevereiro")] = std::string("February");
hm[std::string("março")] = std::string("March");
hm[std::string("abril")] = std::string("April");
hm[std::string("maio")] = std::string("May");
hm[std::string("junho")] = std::string("June");
hm[std::string("julho")] = std::string("July");
hm[std::string("agosto")] = std::string("August");
hm[std::string("setembro")] = std::string("September");
hm[std::string("outubro")] = std::string("October");
hm[std::string("novembro")] = std::string("November");

//-- Searching for the translation of the months "março" and "dezembro" in the map
//-- (dezembro was not put into the map, so you can not find the corresponding element "December")
it = hm.find(std::string("março"));
if(it != hm.end())
std::cout <<"The value corresponding to the key 'março' is "<< it->second << std::endl;
else
std::cout <<"The value corresponding to the key 'março' was not found"<< std::endl;

it = hm.find(std::string("dezembro"));
if(it != hm.end())
std::cout <<"The value corresponding to the key 'dezembro' is "<< it->second << std::endl;
else
std::cout <<"The value corresponding to the key 'dezembro' was not found"<< std::endl;

//-- Listing the pairs key, value (they're not ordered.)
for(it = hm.begin(); it != hm.end(); ++it)
{
std::cout <<"Key = \'"<< it->first <<"\' -> value = \'"<< it->second <<"\'"<< std::endl;
}
}

TAG: 与目前工作有关的杂项

 

评分:0

我来说两句

Open Toolbar