c++ - How to use the (the Boost Multidimensional Array Library) to construct a dynamic two-dimensional array? -


i need in using boost multidimensional array. have construct 2 dimensional array where: (0 <= j <= 1) , (i) grows dynamically according to:

long boostarray[i][j]; 

thus, it's constructing table of (unknown) columns , 2 rows.

i started example provided @ boost library website:

#include "boost/multi_array.hpp" #include <cassert>  int main () {   // 3 x 4 x 2    typedef boost::multi_array<double, 3> array_type;   typedef array_type::index index;   array_type a(boost::extents[3][4][2]);    int values = 0;   for(index = 0; != 3; ++i)      for(index j = 0; j != 4; ++j)       for(index k = 0; k != 2; ++k)         a[i][j][k] = values++;    int verify = 0;   for(index = 0; != 3; ++i)      for(index j = 0; j != 4; ++j)       for(index k = 0; k != 2; ++k)         assert(a[i][j][k] == verify++);    return 0; } 

the problem didn't thoroughly understand above code in order tweak on structure , build desired array. don't know precisely how add/delete elements to/from array while using boost library if array grows dynamically described above.

for example, when dealing vectors, tend use: push_back , pop_back after resizing vector.

for particular usecase, you're better off using vector<pair<t,t>> or vector<array<t,2>>. can use push_back, , it's efficient. boost::multi_array sounds overkill, otoh:

you can't use push_back there, because whenever extend 1 dimension of n-dimensional array, you'd need supply slice of n-1 dimensions of initial data. not efficient, esp. since can add dimension largest stride in way. need use instead resize , assignment.

// std::vector<> equivalent (with vector<>, it's considered bad style) v.resize( v.size() + 1 ); v[v.size()-1] = newelement;  // boost::multi_array (from tutorial) typedef boost::multi_array<int, 3> array_type;  array_type::extent_gen extents; array_type a(extents[3][3][3]); a[0][0][0] = 4; a[2][2][2] = 5; // here, it's way: a.resize(extents[2][3][4]); assert(a[0][0][0] == 4); // a[2][2][2] no longer valid. 

to reiterate: n-dimensional arrays, n>2, inherently less dynamic one-dimensional ones (because of stride factor). above resize requires lot of copying of data, unlike vector case, needs copy data when size()>capacity().


Comments

Popular posts from this blog

objective c - Change font of selected text in UITextView -

php - Accessing POST data in Facebook cavas app -

c# - Getting control value when switching a view as part of a multiview -