summaryrefslogtreecommitdiff
path: root/graphs/cpp/address_book/address_book.cc
blob: 92e74cf140c74b607e0f1c2ddec0762bd974923d (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
//
// Created by martial.simon on 2/26/25.
//

#include "address_book.hh"

#include <iostream>
#include <stdexcept>
bool AddressBook::add(const std::string& full_name, const std::string& email,
                      const std::string& number)
{
    try
    {
        ContactDetails details = ContactDetails::makeDetails(number, email);
        if (full_name.empty())
            return false;
        contact_map_.insert({ full_name, details });
        return true;
    }
    catch (std::invalid_argument& e)
    {
        return false;
    }
}
std::vector<ContactDetails> AddressBook::find(const std::string& full_name)
{
    std::vector<ContactDetails> res;
    for (auto detail = contact_map_.find(full_name);
         detail != contact_map_.end() && detail->first == full_name; detail++)
    {
        res.push_back(detail->second);
    }
    return res;
}
std::size_t AddressBook::count(const std::string& full_name)
{
    size_t res = 0;
    for (auto detail = contact_map_.find(full_name);
         detail != contact_map_.end(); detail++)
    {
        res++;
    }
    return res;
}
bool AddressBook::remove(const std::string& full_name, std::size_t index)
{
    auto range = contact_map_.equal_range(full_name);
    for (auto contact = range.first; contact != range.second; contact++)
    {
        if (contact->first == full_name)
        {
            if (index == 0)
            {
                contact_map_.erase(contact);
                return true;
            }
            index--;
        }
    }
    return false;
}
void AddressBook::remove_all(const std::string& full_name)
{
    auto range = contact_map_.equal_range(full_name);
    contact_map_.erase(range.first, range.second);
}
std::ostream& operator<<(std::ostream& os, const AddressBook& b)
{
    os << b.contact_map_.size() << " contact(s) in the address book.\n";
    for (auto& pair : b.contact_map_)
    {
        os << "- " << pair.first << ": " << pair.second;
    }
    return os;
}