C++: Hash From Two Arrays

Bjarne-stroustrup
 

Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values)

Technically a std::map is a binary search tree, not a hash table, but it provides the same functionality. The C++11 standard incorporates hash tables. To use a hash table in C++11, simply change std::map to std::unordered_map. The core idea, turning two sequences into an associative mapping, is valid either way.

#include <map>
#include <string>

int
main( int argc, char* argv[] )
{
	std::string keys[] = { "1", "2", "3" } ;
	std::string vals[] = { "a", "b", "c" } ;

	std::map< std::string, std::string > hash ;

	for( int i = 0 ; i < 3 ; i++ )
	{
		hash[ keys[i] ] = vals[i] ;
	}
}

Alternatively:

#include <map>       // for std::map
#include <algorithm> // for std::transform
#include <string>    // for std::string
#include <utility>   // for std::make_pair

int main()
{
	std::string keys[] = { "one", "two", "three" };
	std::string vals[] = { "foo", "bar", "baz" };

	std::map<std::string, std::string> hash;

	std::transform(keys, keys+3,
	vals,
	std::inserter(hash, hash.end()),
	std::make_pair<std::string, std::string>);
}

SOURCE

Content is available under GNU Free Documentation License 1.2.