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.13. Implementing a Stride Iterator

Problem

You have a contiguous series of numbers and you want to iterate through the elements n at a time.

Solution

Example 11-24 presents a stride iterator class as a separate header file.

Example 11-24. stride_iter.hpp

#ifndef STRIDE_ITER_HPP #define STRIDE_ITER_HPP #include <iterator> #include <cassert> template<class Iter_T> class stride_iter { public: // public typedefs typedef typename std::iterator_traits<Iter_T>::value_type value_type; typedef typename std::iterator_traits<Iter_T>::reference reference; typedef typename std::iterator_traits<Iter_T>::difference_type difference_type; typedef typename std::iterator_traits<Iter_T>::pointer pointer; typedef std::random_access_iterator_tag iterator_category; typedef stride_iter self; // constructors stride_iter() : m(NULL), step(0) { }; stride_iter(const self& x) : m(x.m), step(x.step) { } stride_iter(Iter_T x, difference_type n) : m(x), step(n) { } // operators self& operator++() { m += step; return *this; } self operator++(int) { self tmp = *this; m += step; return tmp; } self& operator+=(difference_type x) { m += x * step; return *this; } self& operator--() { m -= step; return *this; } self operator--(int) { self tmp = *this; m -= step; return tmp; } self& operator-=(difference_type x) { m -= x * step; return *this; } reference operator[](difference_type n) { return m[n * step]; } reference operator*() { return *m; } // friend operators friend bool operator==(const self& x, const self& y) { ...
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