summaryrefslogtreecommitdiff
path: root/graphs/cpp/int_container/int_container.cc
blob: aabb5abb163a4302ac7df3cf7d77d0ec172f338c (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
78
79
80
81
82
83
#include "int_container.hh"
MyIntContainer::MyIntContainer(size_t size)
    : current_size_{ 0 }
    , max_size_{ size }
    , elems_{ std::make_unique<int[]>(size) }
{}
void MyIntContainer::print() const
{
    if (current_size_ == 0)
        return;
    std::cout << elems_[0];
    for (size_t i = 1; i < current_size_; ++i)
    {
        std::cout << " | " << elems_[i];
    }
    std::cout << "\n";
}
size_t MyIntContainer::get_len() const
{
    return current_size_;
}
bool MyIntContainer::add(int elem)
{
    if (current_size_ == max_size_)
        return false;
    elems_[current_size_++] = elem;
    return true;
}
std::optional<int> MyIntContainer::pop()
{
    if (current_size_ == 0)
        return std::nullopt;
    int res = elems_[--current_size_];
    elems_[current_size_] = -1;
    return res;
}
std::optional<int> MyIntContainer::get(size_t position) const
{
    if (position >= current_size_)
        return std::nullopt;
    return elems_[position];
}
std::optional<size_t> MyIntContainer::find(int elem) const
{
    size_t i;
    for (i = 0; i < current_size_ && elems_[i] != elem; ++i)
        continue;
    if (i == current_size_)
        return std::nullopt;
    return i;
}
void swap(int& a, int& b)
{
    int tmp = a;
    a = b;
    b = tmp;
}
void MyIntContainer::sort()
{
    for (size_t i = 0; i < current_size_ - 1; i++)
    {
        bool flag = false;
        for (size_t j = 0; j < current_size_ - i - 1; j++)
        {
            if (elems_[j] > elems_[j + 1])
            {
                swap(elems_[j], elems_[j + 1]);
                flag = true;
            }
        }
        if (!flag)
            break;
    }
}
bool MyIntContainer::is_sorted() const
{
    for (size_t i = 1; i < current_size_; i++)
    {
        if (elems_[i - 1] > elems_[i])
            return false;
    }
    return true;
}