O'Reilly logo

C++ Cookbook by Jeff Cogswell, Jonathan Turkanis, Christopher Diggins, D. Ryan Stephens

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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) { ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required