Iterators

Creating Custom Iterator Types

How can I create my own custom iterator types that work with standard algorithms?

Abstract art representing computer programming

To create your own custom iterator types that work with standard algorithms, you need to implement the necessary member functions and operators required by the iterator category you want to support.

For example, let's say you have a custom container called MyContainer and you want to create a forward iterator for it. Here's a simplified implementation:

#include <iterator>

template <typename T>
class MyIterator {
 public:
  using iterator_category =
    std::forward_iterator_tag;
  using value_type = T;
  using difference_type = std::ptrdiff_t;
  using pointer = T*;
  using reference = T&;

  MyIterator(pointer ptr) : m_ptr(ptr) {}

  reference operator*() const { return *m_ptr; }
  pointer operator->() { return m_ptr; }
  MyIterator& operator++() {
    m_ptr++;
    return *this;
  }
  MyIterator operator++(int) {
    MyIterator tmp = *this;
    ++(*this);
    return tmp;
  }

  friend bool operator==(const MyIterator& a,
    const MyIterator& b) {
    return a.m_ptr == b.m_ptr;
  };
  friend bool operator!=(const MyIterator& a,
    const MyIterator& b) {
    return a.m_ptr != b.m_ptr;
  };

 private:
  pointer m_ptr;
};

template <typename T>
class MyContainer {
 public:
  using iterator = MyIterator<T>;

  iterator begin() {
    return iterator(&m_data[0]); }
  iterator end() {
    return iterator(&m_data[m_size]); }

 private:
  T m_data[100];
  std::size_t m_size{0};
};

In this example:

  • MyIterator defines the necessary type aliases (iterator_category, value_type, etc.) and implements the required operators for a forward iterator.
  • MyContainer provides begin() and end() member functions that return instances of MyIterator.

Now you can use MyContainer with standard algorithms:

MyContainer<int> container;
// Fill container with data...

std::for_each(container.begin(), container.end(),
  [](int value) { std::cout << value << ' '; }
);

Creating custom iterators allows you to make your custom containers compatible with the rich set of algorithms provided by the standard library, enhancing their flexibility and reusability.

Answers to questions are automatically generated and may not have been reviewed.

Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved