need help for explain the program.

please explain this program. how is it work. i dont understand the unordered_map and algorithm

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
#include <iostream>
#include <unordered_map>
#include <algorithm>
#include <string>


struct text
{
    text() = default;
    text(const std::string& txt) : data(txt) {}

    std::string key() const { std::string k(data); std::sort(k.begin(), k.end()); return k; }

    operator std::pair<std::string, std::string>() const { return std::make_pair(key(), data); }

    std::string data;
};

std::istream& operator>>(std::istream& is, text& t)
{
    return is >> t.data;
}

std::ostream& operator<<(std::ostream& os, const text& t)
{
    return os << t.data;
}

std::string quoted(const text& t)
{
    return std::string(1, '"') + t.data + '"';
}

int main()
{
    using pair_type = std::pair<std::string, std::string> ;

    std::unordered_map<std::string, std::string> map =
    { 
        pair_type(text("scooby")), pair_type(text("shaggy")),  pair_type(text("veronica")),
        pair_type(text("fred")),   pair_type(text("daphne")),  pair_type(text("wilma")),
        pair_type(text("betty")),  pair_type(text("barney")),  pair_type(text("dino")),
        pair_type(text("bambam")), pair_type(text("pebbles")), pair_type(text("george"))
    };

    text t;

    while (std::cin >> t)
    {
        auto it = map.find(t.key());
        if (it != map.end())
            std::cout << quoted(t) << " matches " << quoted(it->second) << '\n';
        else
            std::cout << quoted(t) << " matches nothing\n";
    }
}
std::unordered_map is a container class, a bit like a std::vector. The idea is that it stores everything by key/value pairs, where the keys are unique. It is also stores the values in a hash table, giving you O(1) lookup time, though it relies on there being an available hashing function for that particular key type.

<algorithm> is a header containing a bunch of general-purpose algorithms, which can be used to simplify your life. In this case it is providing the sorting function used on line 12.

Basically, what the program is doing is it is storing a whole bunch of texts in a map, using the conversion operator provided by the structure. It is then inputting data from the user and determining whether the input is found in the data given, i.e. if the same letters are used.
thank u very much. one more favor is that can you simply this program in beginning level. I think this is advance level and beyond my level to understand. It is possible to make it in simple way please help me to simply this program. thanks.
Topic archived. No new replies allowed.