-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathArray.hpp
74 lines (64 loc) · 1.47 KB
/
Array.hpp
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
/*
** EPITECH PROJECT, 2024
** ppool13
** File description:
** Array
*/
#pragma once
#include <array>
#include <functional>
#include <iostream>
template <typename Type, std::size_t _size>
class Array
{
public:
std::size_t size() const
{
return _size;
}
void forEach(const std::function<void(const Type &)> &task) const
{
for (auto &e : _array)
task(e);
}
Type &operator[](std::size_t index)
{
if (index >= _size)
throw OutOfRangeException();
return _array.at(index);
}
const Type &operator[](std::size_t index) const
{
if (index >= _size)
throw OutOfRangeException();
return _array.at(index);
}
template <typename U>
Array<U, _size> convert(
const std::function<U(const Type &)> &converter) const
{
Array<U, _size> res;
for (size_t i = 0; i < _size; i++)
res[i] = converter(_array[i]);
return res;
}
class OutOfRangeException : public std::exception
{
public:
const char *what() const noexcept override
{
return "Out of range";
}
};
private:
std::array<Type, _size> _array{0};
};
template <typename Type, std::size_t _size>
std::ostream &operator<<(std::ostream &os, const Array<Type, _size> &array)
{
os << "[";
for (std::size_t i = 0; i < array.size(); i++)
os << (i ? ", " : "") << array[i];
os << "]";
return os;
}