Hash Maps
This is a list of how to create hash maps and use them in different languages. Not much fun here, more of a reference for me. Might add more content here later.
Java
Basic
// import
import java.util.HashMap;
// create, no type arguments needed to constructor (should work since java 7)
HashMap<String, String> myMap = new HashMap<>();
// insert
myMap.put("drink", "water");
// get
myMap.get("drink");
Go
(Yes, Golang map is implemented as a hash table/map)
Basic
// create
var myMap = make(map[string]string)
// insert
myMap["drink"] = "water"
// get
myMap["drink"]
Rust
Basic
// import
use std::collections::HashMap;
// create, types are inferred
let mut my_map = HashMap::new();
// insert
my_map.insert(
"drink".to_string(),
"water".to_string(),
);
// get
my_map["drink"];
Basic
Python
(Same here, internally python dicts are hash maps/tables)
# create an empty dict
dict = {}
# insert
dict["drink"] = "water"
# get
dict.get("drink")
# or
dict["drink"]
C++
Basic
// include
#include <map>
#include <string>
// create
std::map<std::string, std::string> myMap;
// insert (will overwrite old value, if any)
myMap["drink"] = "water";
// or (will not overwrite, instead ignores new value)
myMap.insert(std::make_pair("dring", "water"));
// get
myMap["drink"];
Static initialization of member map
mapclass.h:
#include <map>
#include <string>
class MapClass {
public:
static std::map<std::string, int> theMap;
MapClass();
};
main.cc:
#include "mapclass.h"
#include <iostream>
std::map<std::string, int> MapClass::theMap = {
{"x", 1}
};
int main (int argc, char *argv[])
{
std::cout << MapClass::theMap["x"] << std::endl;
return 0;
returns 1
Read other posts