11.9. Representing a Fixed-Size Numerical Vector

Problem

You want an efficient representation for manipulating constant-sized numerical vectors

Solution

On many common software architectures, it is more efficient to use a custom vector implementation than a valarray when the size is known at compile time. Example 11-17 provides a sample implementation of a fixed-size vector template called a kvector.

Example 11-17. kvector.hpp

#include <algorithm> #include <cassert> template<class Value_T, unsigned int N> class kvector { public: // public fields Value_T m[N]; // public typedefs typedef Value_T value_type; typedef Value_T* iterator; typedef const Value_T* const_iterator; typedef Value_T& reference; typedef const Value_T& const_reference; typedef size_t size_type; // shorthand for referring to kvector typedef kvector self; // member functions template<typename Iter_T> void copy(Iter_T first, Iter_T last) { copy(first, last, begin()); } iterator begin() { return m; } iterator end() { return m + N; } const_iterator begin() const { return m; } const_iterator end() const { return m + N; } reference operator[](size_type n) { return m[n]; } const_reference operator[](size_type n) const { return m[n]; } static size_type size() { return N; } // vector operations self& operator+=(const self& x) { for (int i=0; i<N; ++i) m[i] += x.m[i]; return *this; } self& operator-=(const self& x) { for (int i=0; i<N; ++i) m[i] -= x.m[i]; return *this; } // scalar operations self& operator=(value_type x) { ...

Get C++ Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.