summaryrefslogtreecommitdiffhomepage
path: root/examples/words.c
blob: 08563cfc1cfb2526a9b35e3776b5e9d2aeb17c4e (plain)
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

#include <stc/cstr.h>
#include <stc/cmap.h>
#include <stc/clist.h>
#include <stc/cvec.h>

using_cvec_str();
using_clist_str();
using_cmap_strkey(si, int);


int main1()
{
    c_init (clist_str, lwords, {
        "this", "sentence", "is", "not", "a", "sentence",
        "this", "sentence", "is", "a", "hoax"
    });

    clist_str_push_back(&lwords, cstr_from_fmt("%f", 123897.0 / 23.0));
    c_foreach (w, clist_str, lwords)
        printf("%s\n", w.ref->str);
    puts("");

    c_init (cvec_str, words, {
        "this", "sentence", "is", "not", "a", "sentence",
        "this", "sentence", "is", "a", "hoax"
    });

    cmap_si word_map = cmap_si_init();
    c_foreach (w, cvec_str, words)
        cmap_si_emplace(&word_map, w.ref->str, 0).first->second += 1;

    c_foreach (i, cmap_si, word_map) {
        printf("%d occurrences of word '%s'\n", i.ref->second, i.ref->first.str);
    }

    cmap_si_del(&word_map);
    cvec_str_del(&words);
    return 0;
}

#ifdef __cplusplus
#include <string>
#include <iostream>
#include <vector>
#include <unordered_map>

int main2()
{
    std::vector<std::string> words = {
        "this", "sentence", "is", "not", "a", "sentence",
        "this", "sentence", "is", "a", "hoax"
    };

    std::unordered_map<std::string, size_t>  word_map;
    for (const auto &w : words) {
        ++word_map[w];
    }

    for (const auto &pair : word_map) {
        std::cout << pair.second
                  << " occurrences of word '"
                  << pair.first << "'\n";
    }
    return 0;
}

int main() {
    main1();
    puts("");
    main2();
}
#else
int main() {
    main1();
}
#endif