File: dump_nested.cc

package info (click to toggle)
parallel-hashmap 1.4.1%2Bds-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 3,872 kB
  • sloc: cpp: 20,492; ansic: 1,114; python: 492; makefile: 85; haskell: 56; perl: 43; sh: 23
file content (88 lines) | stat: -rw-r--r-- 1,771 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/*
 *
 * Example of dumping a map, containing values which are phmap maps or sets
 * building this requires c++17 support
 *
 */

#include <iostream>
#include <parallel_hashmap/phmap_dump.h>

template <class K, class V>
class MyMap : public phmap::flat_hash_map<K, phmap::flat_hash_set<V>>
{
public:
    using Set = phmap::flat_hash_set<V>;

    void dump(const std::string &filename) 
    {
        phmap::BinaryOutputArchive ar_out (filename.c_str());

        ar_out.saveBinary(this->size());
        for (auto& [k, v] : *this) 
        {
            ar_out.saveBinary(k);
            ar_out.saveBinary(v);
        }
    }

    void load(const std::string & filename) 
    {
        phmap::BinaryInputArchive ar_in(filename.c_str());

        size_t size;
        ar_in.loadBinary(&size);
        this->reserve(size);

        while (size--)
        {
            K k;
            Set v;

            ar_in.loadBinary(&k);
            ar_in.loadBinary(&v);

            this->insert_or_assign(std::move(k), std::move(v));
        }
    }

    void insert(K k, V v) 
    {
        Set &set = (*this)[k];
        set.insert(v);
    }

    friend std::ostream& operator<<(std::ostream& os, const MyMap& map)
    {
        for (const auto& [k, m] : map)
        {
            os << k << ": [";
            for (const auto& x : m)
                os << x << ", ";
            os << "]\n";
        }
        return os;
    }
};

int main()
{
    MyMap<size_t, size_t> m;
    m.insert(1, 5);
    m.insert(1, 8);
    m.insert(2, 3);
    m.insert(1, 15);
    m.insert(1, 27);
    m.insert(2, 10);
    m.insert(2, 13);
    
    std::cout << m << "\n";
    
    m.dump("test_archive");
    m.clear();
    m.load("test_archive");
    
    std::cout << m << "\n";

    return 0;
}