TinyRobotics
Loading...
Searching...
No Matches
VectorFromArray.h
1#pragma once
2#include <array>
3#include <cstddef>
4#include <stdexcept>
5
6namespace tinyrobotics {
7
8/**
9 * @brief A simple, fixed-capacity vector backed by std::array for embedded and
10 * performance-critical use.
11 *
12 * VectorFromArray provides a subset of the std::vector API, but with no dynamic
13 * memory allocation. All storage is allocated at compile time, making it
14 * suitable for microcontrollers, real-time systems, or any environment where
15 * heap usage is undesirable or unavailable.
16 *
17 * Features:
18 * - push_back() to add elements up to the fixed capacity N
19 * - operator[] for element access (no bounds checking)
20 * - size() and capacity() for querying current and maximum size
21 * - clear() to reset the vector to empty
22 * - begin()/end() iterators for range-based for loops
23 *
24 * Limitations:
25 * - Capacity is fixed at compile time (template parameter N)
26 * - Exceeding capacity throws std::out_of_range (can be changed for embedded
27 * use)
28 * - No erase, insert, or dynamic resizing
29 *
30 * @ingroup utils
31 *
32 * Example usage:
33 * @code
34 * VectorFromArray<int, 8> v;
35 * v.push_back(1);
36 * v.push_back(2);
37 * for (auto x : v) {
38 * Serial.println(x);
39 * }
40 * v.clear();
41 * @endcode
42 *
43 * @tparam T Element type
44 * @tparam N Maximum number of elements (capacity)
45 */
46template <typename T, std::size_t N>
47class VectorFromArray {
48 public:
49 VectorFromArray() : sz(0) {}
50
51 bool push_back(const T& value) {
52 if (sz >= N) return false;
53 data[sz++] = value;
54 return true;
55 }
56
57 void clear() { sz = 0; }
58
59 std::size_t size() const { return sz; }
60 constexpr std::size_t capacity() const { return N; }
61
62 T& operator[](std::size_t idx) { return data[idx]; }
63 const T& operator[](std::size_t idx) const { return data[idx]; }
64
65 T* begin() { return data.begin(); }
66 T* end() { return data.begin() + sz; }
67 const T* begin() const { return data.begin(); }
68 const T* end() const { return data.begin() + sz; }
69
70 protected:
71 std::array<T, N> data;
72 std::size_t sz;
73};
74
75} // namespace tinyrobotics
A simple, fixed-capacity vector backed by std::array for embedded and performance-critical use.
Definition: VectorFromArray.h:47