Skip to Main Content
C++ Cookbook
book

C++ Cookbook

by D. Ryan Stephens, Christopher Diggins, Jonathan Turkanis, Jeff Cogswell
November 2005
Beginner to intermediate content levelBeginner to intermediate
594 pages
16h 23m
English
O'Reilly Media, Inc.
Content preview from C++ Cookbook

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) { ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C++ System Programming Cookbook

C++ System Programming Cookbook

Onorato Vaticone

Publisher Resources

ISBN: 0596007612Supplemental ContentErrata Page