Browse DevX
Sign up for e-mail newsletters from DevX


Spruce Up Your Built-in Arrays-2 : Page 2




Building the Right Environment to Support AI, Machine Learning and Deep Learning

Step 1: Array Wrapping
The following array_wrapper class template, originally presented by Bjarne Stroustrup, wraps a built-in array in a class that has no additional data members and therefore incurs no space overhead. Unlike ordinary STL containers, array_wrapper allocates its array statically on the stack, just as built-in arrays do. Most importantly, it provides the standard interface that other STL components recognize:

template <class T, int sz> struct array_wrapper { //uniform typedefs used in STL algorithms and containers typedef T value_type; typedef T* iterator; typedef const T * const_iterator; typedef T& reference; typedef const T& const_reference; T v[sz]; //the actual array; no other data members here // member functions of typical STL containers operator T* () {return v;} reference operator[] (size_t idx) {return v[idx];} const_reference operator[] (size_t idx) const {return v[idx];} iterator begin() {return v;} const_iterator begin() const {return v;} iterator end() {return v+sz;} const_iterator end() const {return v+sz;} size_t size() const {return sz;} };

This class is designed for utmost efficiency. It has neither a constructor nor a destructor. Additionally, all its member functions are inlined.

You initialize an array_wrapper as you would a built-in array. The resulting object can be used wherever a built-in array is expected:

void func(int *, int sz); // C function //wrap an array of 20 int's & initialize all members to 0 array_wrapper <int, 20> arr={0}; func(arr, arr.size()); //using T* conversion operator

Let's see how advantageous STL compatibility is. The following example uses the copy() algorithm and an ostream_iterator to display the contents of arr on the screen—as if it were an STL container:

copy(arr.begin(), arr.end(), ostream_iterator<int>(cout, " "));

The C++98 Standard Library doesn't define this class template. However, it will be added in the next revision round. In the meantime, you can download a similar class from Boost or roll your own.

Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date