dump_nested.cc 1.73 KB
Newer Older
limm's avatar
limm committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/*
 *
 * 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());

limm's avatar
limm committed
21
        ar_out.saveBinary(this->size());
limm's avatar
limm committed
22
23
        for (auto& [k, v] : *this) 
        {
limm's avatar
limm committed
24
25
            ar_out.saveBinary(k);
            ar_out.saveBinary(v);
limm's avatar
limm committed
26
27
28
29
30
31
32
33
        }
    }

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

        size_t size;
limm's avatar
limm committed
34
        ar_in.loadBinary(&size);
limm's avatar
limm committed
35
36
37
38
39
40
41
        this->reserve(size);

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

limm's avatar
limm committed
42
43
            ar_in.loadBinary(&k);
            ar_in.loadBinary(&v);
limm's avatar
limm committed
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

            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;
}