add zig codes for Section 'Hash Map'

pull/249/head
sjinzh 2 years ago
parent 3d1937e3c6
commit 71a56f94c8

@ -160,6 +160,20 @@ pub fn build(b: *std.build.Builder) void {
const run_step_array_stack = b.step("run_array_stack", "Run array_stack");
run_step_array_stack.dependOn(&run_cmd_array_stack.step);
// Section: "Hash Map"
// Source File: "chapter_hashing/hash_map.zig"
// Run Command: zig build run_hash_map
const exe_hash_map = b.addExecutable("hash_map", "chapter_hashing/hash_map.zig");
exe_hash_map.addPackagePath("include", "include/include.zig");
exe_hash_map.setTarget(target);
exe_hash_map.setBuildMode(mode);
exe_hash_map.install();
const run_cmd_hash_map = exe_hash_map.run();
run_cmd_hash_map.step.dependOn(b.getInstallStep());
if (b.args) |args| run_cmd_hash_map.addArgs(args);
const run_step_hash_map= b.step("run_hash_map", "Run hash_map");
run_step_hash_map.dependOn(&run_cmd_hash_map.step);
// Section: "Bubble Sort"
// Source File: "chapter_sorting/bubble_sort.zig"
// Run Command: zig build run_bubble_sort

@ -0,0 +1,55 @@
// File: hash_map.zig
// Created Time: 2023-01-13
// Author: sjinzh (sjinzh@gmail.com)
const std = @import("std");
const inc = @import("include");
// Driver Code
pub fn main() !void {
//
var map = std.AutoHashMap(i32, []const u8).init(std.heap.page_allocator);
//
defer map.deinit();
//
// (key, value)
try map.put(12836, "小哈");
try map.put(15937, "小啰");
try map.put(16750, "小算");
try map.put(13276, "小法");
try map.put(10583, "小鸭");
std.debug.print("\n添加完成后,哈希表为\nKey -> Value\n", .{});
inc.PrintUtil.printHashMap(i32, []const u8, map);
//
// key value
var name = map.get(15937).?;
std.debug.print("\n输入学号 15937 ,查询到姓名 {s}\n", .{name});
//
// (key, value)
_ = map.remove(10583);
std.debug.print("\n删除 10583 后,哈希表为\nKey -> Value\n", .{});
inc.PrintUtil.printHashMap(i32, []const u8, map);
//
std.debug.print("\n遍历键值对 Key->Value\n", .{});
inc.PrintUtil.printHashMap(i32, []const u8, map);
std.debug.print("\n单独遍历键 Key\n", .{});
var it = map.iterator();
while (it.next()) |kv| {
std.debug.print("{}\n", .{kv.key_ptr.*});
}
std.debug.print("\n单独遍历值 value\n", .{});
it = map.iterator();
while (it.next()) |kv| {
std.debug.print("{s}\n", .{kv.value_ptr.*});
}
const getchar = try std.io.getStdIn().reader().readByte();
_ = getchar;
}

@ -46,6 +46,16 @@ pub fn printLinkedList(comptime T: type, node: ?*ListNode(T)) !void {
}
}
// Print a HashMap
pub fn printHashMap(comptime TKey: type, comptime TValue: type, map: std.AutoHashMap(TKey, TValue)) void {
var it = map.iterator();
while (it.next()) |kv| {
var key = kv.key_ptr.*;
var value = kv.value_ptr.*;
std.debug.print("{} -> {s}\n", .{key, value});
}
}
// This tree printer is borrowed from TECHIE DELIGHT
// https://www.techiedelight.com/c-program-print-binary-tree/
const Trunk = struct {

Loading…
Cancel
Save