The following gives the code for a 2D array based on boost::multi_array. The code supports retrieval of arbitrary rows and columns. The code uses some features of C++ 11x. So use the appropriate compiler flag to compile the code.
Application Code:
#include "array2d.h"
#include <vector>
#include <iterator>
#include <iostream>
using namespace std;
int main(){
//defining the array
Array2d<int> array(2,5);
//populating it
Array2d<int>::element * itr = array.data();
for(int i = 0; i < 10; i++){
*itr++ = i;
}
//getting an arbitrary row
vector<int>r;
array.row<1>(back_inserter(r));
copy(r.begin(),r.end(),ostream_iterator<int>(cout," "));
cout << endl;
//getting an arbitrary column
vector<int>c;
array.col<2>(back_inserter(c));
copy(c.begin(),c.end(),ostream_iterator<int>(cout," "));
return 0;
}
The array class definition is given below:
#ifndef ARRAY_H_
#define ARRAY_H_
#include <boost/multi_array.hpp>
#include <algorithm>
#include <iostream>
#include "mystrcat.h"
#include <stdexcept>
using namespace std;
template <class T>
class Array2d{
public:
typedef typename boost::multi_array<T,2> array_type;
typedef typename array_type::element element;
typedef boost::multi_array_types::index_range range;
Array2d(uint rows, uint cols);
element * data();
void display();
template<int c, class Itr>
void col(Itr itr); //dumps the cth column to the container pointed to by itr
template<int r, class Itr>
void row(Itr itr); //dumps the rth row to the container pointed to by itr
private:
array_type array;
uint rows;
uint cols;
};
template <class T>
Array2d<T>::Array2d(uint _rows, uint _cols):rows(_rows),cols(_cols){
array.resize(boost::extents[rows][cols]);
}
template <class T>
typename Array2d<T>::element* Array2d< T >::data(){
return array.data();
}
template<class T>
template<int c, class Itr>
void Array2d<T>::col(Itr itr) {
//copies column c to the given container
if (c < 0 || c >= cols) throw runtime_error(Mystrcat("Only", cols, "columns available and you asked for column",c));
typename array_type::template array_view<1>::type myview =
array[boost::indices[range()][c]];
std::copy(myview.begin(), myview.end(), itr);
}
template<class T>
template<int r, class Itr>
void Array2d<T>::row(Itr itr) {
//copies row r to the given container
if (r < 0 || r >= rows) throw runtime_error(Mystrcat("Only", rows, "rows available and you asked for row",r));
typename array_type::template array_view<1>::type myview =
array[boost::indices[r][range()]];
std::copy(myview.begin(), myview.end(), itr);
}
template <class T>
void Array2d<T>::display(){
for (auto i = array.data(); i < array.data()+array.num_elements(); i++)
cout << *i << endl;
}
#endif /* 2DARRAY_H_ */
Recent Comments