Taz bisounours-codeur | ignoble
Code :
- #include <cstddef>
- #include <new>
- #ifdef DEBUG
- #include <iostream>
- #endif
- template<typename T>
- T** make(size_t d1, size_t d2)
- {
- T **matrix;
- unsigned char *storage;
- size_t header_size, data_size;
- header_size = d1 * sizeof(T*);
- data_size = d1 * d2 * sizeof(T);
- storage = new unsigned char[header_size + data_size];
- #ifdef DEBUG
- std::cout << "Allocated " << (header_size + data_size) << "B at "
- << static_cast<void*>(storage) << '\n'
- << "header size = " << header_size << "B \n"
- << "data_size = " << data_size << "B \n";
- #endif
- matrix = new (storage) T*[d1];;
- for(size_t i = 0; i < d1; ++i)
- {
- size_t offset = 0;
- offset += header_size;
- offset += d2 * i * sizeof(T);
- #ifdef DEBUG
- std::cout << "Allocated " << (d2 * sizeof(T)) << "B at "
- << static_cast<void*>(storage + offset) << '\n';
- #endif
- matrix[i] = new (storage + offset) T[d2];
- }
- return matrix;
- }
- template<typename M, typename E>
- void fill3(M &m, size_t x, size_t y, size_t z, const E &e)
- {
- for(size_t i = 0; i < x; ++i)
- for(size_t j = 0; j < y; ++j)
- for(size_t k = 0; k < z; ++k)
- m[i][j][k] = e;
- }
- template<typename M, typename N>
- bool equal3(const M &m, const N &n, size_t x, size_t y, size_t z)
- {
- for(size_t i = 0; i < x; ++i)
- for(size_t j = 0; j < y; ++j)
- for(size_t k = 0; k < z; ++k) {
- if(m[i][j][k] != n[i][j][k]) return false;
- }
- return true;
- }
- int main()
- {
- const size_t X = 10, Y = 20, Z = 30;
- typedef double Inner[Z];
- Inner **m1, **m2;
- m1 = new Inner*[X];
- for(size_t i = 0; i < X; ++i)
- m1[i] = new Inner[Y];
- m2 = make<Inner>(X, Y);
- fill3(m1, X, Y, Z, 3.14);
- fill3(m2, X, Y, Z, 3.14);
- bool eq = equal3(m1, m2, X, Y, Z);
- for(size_t i = 0; i < X; ++i)
- delete m1[i];
- delete m1;
- delete m2;
- return eq;
- }
|
un petit exemple avec 2 techniques pour faire des allocations plus sympa pour la fragmentation de la mémoire.
1) vu que la taille des éléments interne est fixe (pour toi double[3]) et bien il faut s'en servir -> m1
2) j'avais dans un coin un truc pour allouer une matrice de manière contigüe. une matrice2D de double[3] et voilà, c'est plié. |