- Joined
- Jul 10, 2007
- Messages
- 6,306
So, have you ever gotten tired of creating and initializing dynamic multi-dimensional arrays? Destroying them is a pain too.
Well, I created some functions that'll do it for you ^)^. They will take any number of dimensions with a size for each dimension.
Warning: mad c++ abuse
Well, I created some functions that'll do it for you ^)^. They will take any number of dimensions with a size for each dimension.
Warning: mad c++ abuse
C++:
#pragma once
/*
* void* nd_array(const std::initializer_list<int>& dimensions)
* - auto i = nd_array<int, int***>({ 1, 2, 3 });
*
* void nd_array_free(void* arr, const std::initializer_list<int>& dimensions)
* - nd_array_free<int>(i, { 1, 2, 3 });
*
* void nd_array_set(void* arr, const std::initializer_list<int>& dimensions, const T val)
* - nd_array_set<int>(i, { 1, 2, 3 }, 1)
*/
#include <stdint.h>
#include <initializer_list>
using namespace std;
template <class T>
void nd_array(uintptr_t* arr, const int* dim, const int* len) {
if (dim < len - 1) {
for (int i = 0; i < *(dim - 1); ++i) {
*(uintptr_t**)(arr + i) = new uintptr_t[*dim];
nd_array<T>((uintptr_t*) *(arr + i), dim + 1, len);
}
}
else {
for (int i = 0; i < *(dim - 1); ++i) {
*(T**) (arr + i) = new T[*dim];
}
}
}
template <class T, class T2>
T2 nd_array(const std::initializer_list<int>& dimensions) {
int* dim = new int[dimensions.size()];
int i = 0;
for (auto it = dimensions.begin(); it != dimensions.end(); ++it) {
dim[i++] = *it;
}
auto arr = new uintptr_t[*dim];
nd_array<T>(arr, dim + 1, dimensions.size() + dim);
delete [] dim;
return (T2)arr;
}
template <class T>
void nd_array_free(uintptr_t* arr, const int* dim, const int* len) {
if (dim < len - 1) {
for (int i = 0; i < *(dim - 1); ++i) {
nd_array_free<T>((uintptr_t*) *(arr + i), dim + 1, len);
delete [] * (uintptr_t**) (arr + i);
}
}
else {
for (int i = 0; i < *(dim - 1); ++i) {
delete [] * (T**) (arr + i);
}
}
}
template <class T>
void nd_array_free(void* arr, const std::initializer_list<int>& dimensions) {
int* dim = new int[dimensions.size()];
int i = 0;
for (auto it = dimensions.begin(); it != dimensions.end(); ++it) {
dim[i++] = *it;
}
nd_array_free<T>((uintptr_t*)arr, dim + 1, dimensions.size() + dim);
delete [] arr;
delete [] dim;
}
template <class T>
void nd_array_set(uintptr_t* arr, const int* dim, const int* len, const T val) {
if (dim < len) {
for (int i = 0; i < *(dim - 1); ++i) {
nd_array_set<T>((uintptr_t*) *(arr + i), dim + 1, len, val);
}
}
else {
for (int i = 0; i < *(dim - 1); ++i) {
*(T*) (arr + i) = val;
}
}
}
template <class T>
void nd_array_set(void* arr, const std::initializer_list<int>& dimensions, const T val) {
int* dim = new int[dimensions.size()];
int i = 0;
for (auto it = dimensions.begin(); it != dimensions.end(); ++it) {
dim[i++] = *it;
}
nd_array_set<T>((uintptr_t*) arr, dim + 1, dimensions.size() + dim, val);
delete [] dim;
}