Files
snipplib/examples/hmap_example.cpp
Timur A. Fatkhullin a95a3a5d1b ...
2026-06-18 00:31:08 +03:00

119 lines
3.3 KiB
C++

#include <print>
#include <snipplib/containers/snplib_hmap.h>
using namespace snplib;
int main()
{
int i = 10;
double d = 7.7;
std::string s = "klewjdl";
HeterogenMap<std::string_view> hmap;
bool ok = hmap.push("int_key", i, std::tuple<double, float, long>{});
if (!ok) {
std::println("cannot insert integer value {}", i);
}
ok = hmap.push("str_key", s);
if (!ok) {
std::println("cannot insert string value {}", s);
}
ok = hmap.push("dbl_key", d, std::tuple<double, float, long, int>{});
if (!ok) {
std::println("cannot insert double value {}", d);
}
auto rd = hmap.get<double>("int_key");
if (rd) {
std::println("hmap[int_key] = {}", rd.value());
} else {
std::println("cannot convert to double value with key 'int_key'");
}
auto rl = hmap.get<long>("dbl_key");
if (rl) {
std::println("hmap[dbl_key] = {}", rl.value());
} else {
std::println("cannot convert to long value with key 'dbl_key'");
}
std::println("\n{:*^80}", " copy ctor ");
HeterogenMap<std::string_view> hmap_copy(hmap);
auto rs = hmap.get<std::string>("str_key");
if (rs) {
std::println("hmap['str_key'] = {}", rs.value());
} else {
std::println("cannot get hmap['str_key']");
}
rs = hmap_copy.get<std::string>("str_key");
if (rs) {
std::println("hmap_copy['str_key'] = {}", rs.value());
} else {
std::println("cannot get hmap_copy['str_key']");
}
std::println("\n{:*^80}", " move ctor ");
HeterogenMap<std::string_view> hmap_move(std::move(hmap));
std::println("contains hmap_move['str_key']: {}", hmap_move.contains("str_key"));
rs = hmap_move.get<std::string>("str_key");
if (rs) {
std::println("hmap_move['str_key'] = {}", rs.value());
} else {
std::println("cannot get hmap_move['str_key']");
}
rs = hmap.get<std::string>("str_key");
if (rs) {
std::println("hmap['str_key'] = {}", rs.value());
} else {
std::println("cannot get hmap['str_key']");
std::println("contains hmap['str_key']: {}", hmap.contains("str_key"));
}
std::println("\n{:*^80}", " set value ");
double dd = 123.456789;
std::println("set hmap_copy['int_key'] to {} ...", dd);
if (hmap_copy.set("int_key", dd)) {
std::println("cannot set hmap_copy['int_key'] to {}", dd);
} else {
auto ri = hmap_copy.get<int>("int_key");
if (ri) {
std::println("hmap_copy['int_key'] = {}", ri.value());
} else {
std::println("cannot get value of hmap_copy['int_key']");
}
}
std::println("\n{:*^80}", " delete key ");
std::println("erase node with key 'int_key'");
if (hmap_move.erase("int_key")) {
auto ri = hmap_move.get<int>("int_key");
if (ri) { // should not be
std::println("hmap_move['int_key'] = {}", ri.value());
} else {
std::println("cannot get value of hmap_move['int_key']");
}
ri = hmap_copy.get<int>("int_key");
if (ri) {
std::println("hmap_copy['int_key'] = {}", ri.value());
} else {
std::println("cannot get value of hmap_copy['int_key']");
}
}
return 0;
}