-
Notifications
You must be signed in to change notification settings - Fork 0
/
BaseArray.h
674 lines (597 loc) · 23.5 KB
/
BaseArray.h
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
#ifndef BASE_ARRAY_H
#define BASE_ARRAY_H
#include "Object.h"
#include "Unique.h"
#include <functional>
#include <iostream>
/**
* @brief This class wraps an array of a *constant size*, and `delete`s it on
* destruction.
*
* Use this class instead of the old fashioned way:
* @code
* CLASS_TYPE *classTypeArray = new CLASS_TYPE [someDynamicSize];
* @endcode
* to *avoid* concerning yourself with the need to `delete` the allocated
* array afterwards.
*
* For example:
* How to use this class:
* All the below examples work perfectly, and you don't need to ever again
* use the `delete` keyword.
*
* @code
* auto testArray = BaseArray<std::string>(1);
*
* // Example: "inline rvalue"
* testArray.setElement(getLine(std::cin), 0);
* std::cout << testArray << std::endl;
*
* // Example: "normal lvalue. convert it to a rvalue to insert"
* std::string str = getLine(std::cin);
* testArray.setElement((std::string str &&) str, 0);
* std::cout << testArray << std::endl;
*
* // Example: "inline anonymous heap allocated lvalue"
* testArray.setElement(new std::string(getLine(std::cin)), 0, true);
* std::cout << testArray << std::endl;
*
* // Example: "external heap allocated lvalue"
* std::string *str = new std::string(getLine(std::cin));
* testArray.setElement(str, 0);
* std::cout << testArray << std::endl;
* delete str;
* @endcode
*
* @note DEVELOPER NOTE: You must ensure that the `BaseArray<E>::_physicalSize`
* is larger than the logical-`size` by `1` at all times.
* @tparam E the type of `element` in the array.
*
* @see Unique
* @version 1.0.6
*/
template<typename E> class BaseArray : public Object {
protected:
static constexpr char *PHYSICAL_SIZE_MESSAGE =
(char *) "BaseArray: `physicalSize` must be at least `1`.";
protected:
static constexpr char *OUT_OF_RANGE_MESSAGE =
(char *) "BaseArray: out of range.";
protected:
static constexpr char *SIZE_OUT_OF_RANGE_MESSAGE =
(char *) "BaseArray: size is out of range.";
protected:
static constexpr char *ELEMENT_IS_NULL_MESSAGE =
(char *) "BaseArray: Element is `nullptr`.";
protected:
Unique<E> **_array = nullptr;
protected:
/// *Must* be `0` for `move` operation.
unsigned long _physicalSize = 0;
public:
unsigned long size() const { return _physicalSize; }
public:
explicit BaseArray(unsigned long physicalSize) {
if (physicalSize < 1) {
throw std::invalid_argument(PHYSICAL_SIZE_MESSAGE);
}
_physicalSize = physicalSize;
_array = new Unique<E> *[_physicalSize];
initUniqueArray(_array, _physicalSize);
}
protected:
static void initUniqueArray(Unique<E> **&array, unsigned long size) {
for (unsigned long i = 0; i < size; i++) {
array[i] = new Unique<E>(nullptr);
}
}
public:
BaseArray(const BaseArray &other) = delete;
public:
BaseArray(BaseArray &&other) noexcept { *this = std::move(other); }
public:
virtual ~BaseArray() { deleteThis(); }
protected:
void deleteThis() { deleteUniqueArray(_array, _physicalSize); }
protected:
static void deleteUniqueArray(Unique<E> **&array, unsigned long size) {
for (unsigned long i = 0; i < size; i++) { delete array[i]; }
delete[] array;
}
public:
virtual E &getElement(unsigned long index) {
if (isOutOfRange(index)) {
throw std::out_of_range(OUT_OF_RANGE_MESSAGE);
}
E *element = _array[index]->getElement(); // Shallow copy pointer.
return *element;
}
public:
/**
* @param isAnonymous in case the element as an "inline anonymous heap
* allocated lvalue" then, you should set the
* @p isAnonymous to `true`. And that way, `this` array
* will know to `delete` it after its use automatically.
*/
virtual void setElement(E *element, unsigned long index, bool isAnonymous) {
if (isOutOfRange(index)) {
throw std::out_of_range(OUT_OF_RANGE_MESSAGE);
}
auto *unique = new Unique<E>(element);
if (isAnonymous) { unique->setNeedToDeleteElement(true); }
// Delete old element.
delete this->_array[index];
this->_array[index] = unique;
}
public:
virtual void setElement(E &&element, unsigned long index) {
if (isOutOfRange(index)) {
throw std::out_of_range(OUT_OF_RANGE_MESSAGE);
}
auto *unique = new Unique<E>((E &&) element);
// Delete old element.
delete this->_array[index];
this->_array[index] = unique;
}
public:
virtual E *deleteElement(unsigned long index) {
Unique<E> *uniqueDeleted = _array[index];
E * elementDeleted = uniqueDeleted->getElement();
if (!uniqueDeleted->isNeedToDeleteElement()) {
uniqueDeleted = nullptr;
}
return elementDeleted;
}
public:
/**
* @brief This method will *invoke* the given @p callBack function on
* each element in the array.
*
* For example:
* @code
* BaseArray<std::string> baseArray(3);
* baseArray.setElement("32", 0);
* baseArray.setElement("455", 1);
* baseArray.setElement("7678", 2);
* std::cout << baseArray << std::endl;
*
* baseArray.forEach([&baseArray](auto *s) { *s = s->substr(0, 1); });
* // You may also use the explicit option of:
* // baseArray.forEach([&baseArray](std::string *s) { *s = s->substr(0, 1); });
*
* std::cout << baseArray << std::endl;
* @endcode
* will result with the output of:
* @code
* [32 ,455 ,7678]
* [3 ,4 ,7]
* @endcode
*
* Another example:
* @code
* BaseArray<int> baseArray(3);
* baseArray.setElement(32, 0);
* baseArray.setElement(455, 1);
* baseArray.setElement(7678, 2);
* std::cout << baseArray << std::endl;
*
* baseArray.forEach([&baseArray](auto *i) { *i += 1; });
*
* std::cout << baseArray << std::endl;
* @endcode
* will result with the output of:
* @code
* [32 ,455 ,7678]
* [33 ,456 ,7679]
* @endcode
*
* @param callBack a `void` function that each element in the array will
* be invoked with.
* @note You are suggested to use a "lambda" function
* for this function - so that it will be quicker
* for you to use this method.
* @return `this` object. So that you may "chain" this method with another.
*/
virtual BaseArray<E> &forEach(const std::function<void(E *)> &callBack,
unsigned long sizeToIterateOnTo = 0) {
unsigned long sizeToIterateOnToDynamic =
getSizeToIterateOnToDynamic(sizeToIterateOnTo);
for (unsigned long i = 0; i < sizeToIterateOnToDynamic; i++) {
callBack(this->_array[i]->getElement());
}
return *this;
}
public:
/**
* @brief This method will *filter* out from the array the elements that
* do not return `true` the given @p predicate function.
*
* @note in case all of the array got filtered out, then this method will
* return an array of physicalSize of `1` with `nullptr` as its
* first element.
*
* For example:
* @code
* BaseArray<std::string> baseArray(3);
* std::cout << baseArray << std::endl;
* baseArray.filter([&baseArray](auto *s) { return s != nullptr; });
* // You may also use the explicit option of:
* // baseArray.filter([&baseArray](std::string *s) { return s != nullptr; });
* std::cout << baseArray << std::endl;
* @endcode
* will result with the output of:
* @code
* [nullptr ,nullptr ,nullptr]
* [nullptr]
* @endcode
*
* @param predicate a `bool` function such that only the elements that
* are returning `true` to this @p predicate function
* would remain in the array. The others would be
* `deleted` from the array.
* @note You are suggested to use a "lambda" function
* for this function - so that it will be quicker
* for you to use this method.
* @return `this` object. So that you may "chain" this method with another.
*/
virtual BaseArray<E> &filter(const std::function<bool(E *)> &predicate,
unsigned long sizeToIterateOnTo = 0) {
unsigned long sizeToIterateOnToDynamic =
getSizeToIterateOnToDynamic(sizeToIterateOnTo);
unsigned long newArrayPhysicalSize = 0;
/*
* Must iterate over the array twice.
* The `for-loops`' content is:
* 1. Count the `newArraySize`.
* 2. - `insert` the elements that are `true` with the predicate
* given to `newArray`.
*/
for (unsigned long i = 0; i < sizeToIterateOnToDynamic; i++) {
if (predicate(this->_array[i]->getElement())) {
newArrayPhysicalSize++;
}
}
if (!newArrayPhysicalSize) { newArrayPhysicalSize = 1; }
Unique<E> **newArray = new Unique<E> *[newArrayPhysicalSize];
initUniqueArray(newArray, newArrayPhysicalSize);
copyArraysBasedOnPredicate(predicate, newArray);
this->deleteThis();
this->_array = newArray;
this->_physicalSize = newArrayPhysicalSize;
return *this;
}
protected:
void copyArraysBasedOnPredicate(const std::function<bool(E *)> &predicate,
Unique<E> ** newArray) {
copyArraysBasedOnPredicateStatic(_array, newArray, _physicalSize,
predicate);
}
protected:
void copyArraysStatic(Unique<E> **source, Unique<E> **destination,
unsigned long size) {
copyArraysBasedOnPredicateStatic(source, destination, size,
[](auto *) { return true; });
}
protected:
static void copyArraysBasedOnPredicateStatic(
Unique<E> **source, Unique<E> **destination, unsigned long size,
const std::function<bool(E *)> &predicate) {
for (unsigned long i = 0; i < size; i++) {
E *element = source[i]->getElement();
if (predicate(element)) {
/*
* - If element is originally a "lvalue", then shallow-copy the
* pointer.
* - else if the element is originally a "rvalue", then
* deep-copy the pointer.
*/
if (!source[i]->isNeedToDeleteElement()) {
// Shallow-Copy the pointer within unique.
destination[i] = source[i];
} else if (source[i]->isNeedToDeleteElement()) {
// Deep-Copy the pointer within unique.
destination[i] = new Unique<E>(*source[i]);
}
continue;
}
}
}
public:
/**
* @brief This method will *map* out another `Array` from `this` array.
*
* For exmaple:
* @code
* class ObjectTest {
*
* private:
* int _arbitraryInt = 0;
*
* public:
* explicit ObjectTest(int arbitraryInt) { _arbitraryInt = arbitraryInt; }
*
* public:
* friend std::ostream &operator<<(std::ostream & os,
* const ObjectTest &object) {
* os << "_arbitraryInt: " << object._arbitraryInt;
* return os;
* }
* };
*
* // ------------------------------------------------
*
* BaseArray<std::string> baseArray(3);
* baseArray.setElement("32", 0);
* baseArray.setElement("455", 1);
* baseArray.setElement("7678", 2);
* std::cout << baseArray << std::endl;
*
* auto mappedBaseArray = baseArray.map<ObjectTest>(
* [&baseArray](std::string *s) {
* return new ObjectTest(std::atoi(s->c_str()));
* },
* true);
* std::cout << mappedBaseArray << std::endl;
* @endcode
* will result with the output of:
* @code
* [32 ,455 ,7678]
* [_arbitraryInt: 32 ,_arbitraryInt: 455 ,_arbitraryInt: 7678]
* @endcode
*
* Another exmaple:
* @code
* BaseArray<int> baseArray(3);
* baseArray.setElement(32, 0);
* baseArray.setElement(455, 1);
* baseArray.setElement(7678, 2);
* std::cout << baseArray << std::endl;
*
* auto mappedBaseArray = baseArray.map<ObjectTest>(
* [&baseArray](auto *i) { return new ObjectTest(*i); }, true);
* std::cout << mappedBaseArray << std::endl;
* @endcode
* will result with the output of:
* @code
* [32 ,455 ,7678]
* [_arbitraryInt: 32 ,_arbitraryInt: 455 ,_arbitraryInt: 7678]
* @endcode
*
* @tparam E2 the type of `element`s in the returned `Array`.
* @param mapFunction a `E2`-return-type function that each element in
* the array will be invoked with, and *maps* that element
* to another object of type `E2`.
* Afterwards, the elements in `this` array would be
* `deleted` from the array.
* @note You are suggested to use a "lambda" function
* for this function - so that it will be
* quicker for you to use this method.
* @param sizeToIterateOnTo you may pick a different size to-iterate on the
* array. The default size is its physical size, so
* it will iterate on all of it.
* @return the array of type `E2` mapped by `this` array. This way, you
* may also "chain" this method with another.
*/
template<typename E2>
BaseArray<E2> map(const std::function<E2 *(E *)> &mapFunction,
bool isAnonymous = false,
unsigned long sizeToIterateOnTo = 0) {
unsigned long sizeToIterateOnToDynamic =
getSizeToIterateOnToDynamic(sizeToIterateOnTo);
/*
* Must iterate over the array once.
* The `for-loop`'s content is:
* - `insert` the new mapped-elements to `newArray`.
*/
BaseArray<E2> e2Array(sizeToIterateOnToDynamic);
for (unsigned long i = 0; i < sizeToIterateOnToDynamic; i++) {
E *element = this->_array[i]->getElement();
e2Array.setElement(mapFunction(element), i, isAnonymous);
}
return e2Array;
}
public:
// FIXME: need to fix.
// this doesn't work for example with: `std::string` "map &&" to `int`
/**
* @brief This method will *map* out another `Array` from `this` array.
*
* @tparam E2 the type of `element`s in the returned `Array`.
* @param mapFunction a `E2`-return-type function that each element in
* the array will be invoked with, and *maps* that element
* to another object of type `E2`.
* Afterwards, the elements in `this` array would be
* `deleted` from the array.
* @note You are suggested to use a "lambda" function
* for this function - so that it will be
* quicker for you to use this method.
* @param sizeToIterateOnTo you may pick a different size to-iterate on the
* array. The default size is its physical size, so
* it will iterate on all of it.
* @return the array of type `E2` mapped by `this` array. This way, you
* may also "chain" this method with another.
*/
template<typename E2>
BaseArray<E2> map(const std::function<E2 && (E *)> &mapFunction,
unsigned long sizeToIterateOnTo = 0) {
unsigned long sizeToIterateOnToDynamic =
getSizeToIterateOnToDynamic(sizeToIterateOnTo);
/*
* Must iterate over the array once.
* The `for-loop`'s content is:
* - `insert` the new mapped-elements to `newArray`.
*/
BaseArray<E2> e2Array(sizeToIterateOnToDynamic);
for (unsigned long i = 0; i < sizeToIterateOnToDynamic; i++) {
E *element = this->_array[i]->getElement();
e2Array.setElement(mapFunction(element), i);
}
return e2Array;
}
private:
unsigned long getSizeToIterateOnToDynamic(unsigned long sizeToIterateOnTo) {
return getSizeToIterateOnToDynamicStatic(sizeToIterateOnTo,
_physicalSize);
}
public:
static unsigned long
getSizeToIterateOnToDynamicStatic(unsigned long sizeToIterateOnTo,
unsigned long physicalSize) {
unsigned long sizeToIterateOnToDynamic = physicalSize;
if (sizeToIterateOnTo) {
if (isOutOfRangeStatic(sizeToIterateOnTo - 1, physicalSize)) {
std::string msg = (char *) SIZE_OUT_OF_RANGE_MESSAGE;
std::string msg2 =
(char *) "You picked a size that is larger than the "
"current `physicalSize` of :" +
physicalSize;
throw std::out_of_range(msg + " " + msg2);
}
sizeToIterateOnToDynamic = sizeToIterateOnTo;
}
return sizeToIterateOnToDynamic;
}
public:
/**
* @brief Shallow-Copying `this` object.
* @return a shallow-copy of `this` object.
*/
BaseArray<E> ©() {
BaseArray<E> copyArray(_physicalSize);
for (unsigned long i = 0; i < _physicalSize; i++) {
copyArray._array[i] = _array[i]; // Shallow-Copy the reference.
}
return copyArray;
}
protected:
virtual bool isOutOfRange(unsigned long index) {
return isOutOfRangeStatic(index, _physicalSize);
}
public:
static bool isOutOfRangeStatic(unsigned long index,
unsigned long physicalSize) {
// `_physicalSize` *must* be at least 1.
return !((0 <= index) && (index < physicalSize));
}
protected:
void assertNotNull(E *element) {
if (element == nullptr) {
std::string msg = (char *) ELEMENT_IS_NULL_MESSAGE;
std::string msg2 =
(char *) "Use the `getElement(unsigned long)`"
" method to retrieve it, instead of this"
" method.";
throw std::runtime_error(msg + " " + msg2);
}
}
public:
void manipulateElementByRangeOfElements(
unsigned long indexOfElementToManipulate,
unsigned long indexOfFirstElementToManipulateWith,
unsigned long indexOfLastElementToManipulateWith,
const std::function<E(E &, E &)> &callBack) {
for (unsigned long i = indexOfFirstElementToManipulateWith;
i < indexOfLastElementToManipulateWith + 1; i++) {
setElement((E) callBack(getElement(indexOfElementToManipulate),
getElement(i)),
indexOfElementToManipulate);
}
}
public:
void
mergeElements(unsigned long indexOfDestinationElement,
unsigned long indexOfFirstElementToMergeToDestinationElement,
unsigned long indexOfLastElementToMergeToDestinationElement,
const std::function<E(E &, E &)> &callBack) {
manipulateElementByRangeOfElements(
indexOfDestinationElement,
indexOfFirstElementToMergeToDestinationElement,
indexOfLastElementToMergeToDestinationElement, callBack);
shortenArray(indexOfFirstElementToMergeToDestinationElement,
indexOfLastElementToMergeToDestinationElement);
}
public:
void shortenArray(unsigned long startIndexToDeleteFrom,
unsigned long endIndexToDeleteTo) {
auto sizeOfAllTheElementsMerged =
endIndexToDeleteTo + 1 - startIndexToDeleteFrom;
auto newArraySize = _physicalSize - sizeOfAllTheElementsMerged;
Unique<E> **newArray = new Unique<E> *[newArraySize];
for (unsigned long i = 0; i < _physicalSize; i++) {
/*
* Shallow-Copy pointers.
* If the element is marked for `delete`, then don't copy it.
* Instead, `delete` it.
*/
if ((startIndexToDeleteFrom <= i) && (i <= endIndexToDeleteTo)) {
delete _array[i];
continue;
}
newArray[i] = _array[i];
}
// Delete the old array pointer.
delete[] _array;
// Set the new array pointer to `newArray` pointer.
_array = newArray;
// Set the new _physicalSize to `newArraySize`.
_physicalSize = newArraySize;
}
public:
BaseArray &operator=(const BaseArray &other) = delete;
public:
BaseArray &operator=(BaseArray &&other) noexcept {
// Guard self assignment
if (this != &other) {
// Free the existing resource.
deleteThis();
// Copy the all pointers and primitives from the source object.
this->_physicalSize = other._physicalSize;
_array = other._array;
for (unsigned long i = 0; i < _physicalSize; i++) {
_array[i] = other._array[i];
}
/*
* Release the data pointer from the source object so that
* the destructor does not free the memory multiple times.
*/
other.forEach([&other](auto *e) { e = nullptr; });
other._physicalSize = 0;
other._array = nullptr;
}
return *this;
}
public:
friend std::ostream &operator<<(std::ostream &os, const BaseArray &array) {
return print(os, array);
}
public:
/**
* @note This method is `nullptr` resistant - Instead of crashing, it prints
* "nullptr".
*/
static std::ostream &print(std::ostream &os, const BaseArray &array,
unsigned long sizeToIterateOnTo = 0) {
unsigned long sizeToIterateOnToDynamic =
getSizeToIterateOnToDynamicStatic(sizeToIterateOnTo,
array._physicalSize);
os << '[';
if (sizeToIterateOnToDynamic) {
printElement(os, (array._array[0])->getElement());
}
for (unsigned long i = 1; i < sizeToIterateOnToDynamic; i++) {
os << " ,";
printElement(os, (array._array[i])->getElement());
}
os << ']';
return os;
}
protected:
static void printElement(std::ostream &os, E *element) {
if (element == nullptr) {
os << "nullptr";
} else {
os << *element;
}
}
};
#endif // BASE_ARRAY_H