【Rust】ハッシュマップ(Hashmap)

ハッシュマップは文字列を添字に使用することができる。他の言語では連想配列と呼ばれる。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
use std::collections::HashMap;
 
fn main(){
    let mut map = HashMap::new();
    map.insert("x", 10);
    map.insert("y", 20);
    map.insert("z", 30);
 
    println!("{} {} {}", map["x"], map["y"], map["z"]);
 
    for (k, v) in &map {
        println!("{} {}", k, v);
    }
}

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <map>
#include <string>
 
using namespace std;
 
int main()
{
    map<int, string> Players;
 
    Players.insert(std::pair<int, string>(2, "Lin Dan"));
    Players.insert(std::pair<int, string>(1, "Chen Long"));
 
    cout << "Number of Players " << Players.size() << endl;
    for(map<int, string>::iterator it = Players.begin(); it != Players.end();
        ++it){
            cout << (*it).first << ": " << (*it).second << endl;
        }
 
}
1
2
3
4
5
6
7
8
9
10
11
12
13
use std::collections::HashMap;
 
fn main(){
    let mut Players = HashMap::new();
    Players.insert(2, "Lin Dan");
    Players.insert(1, "Chen Long");
 
    println!("{}", Players.len());
 
    for (k, v) in &Players {
        println!("{}: {}", k, v);
    }
}

$ ./main
2
1: Chen Long
2: Lin Dan