Implementing Ranges for Custom Types

What are iterator types in C++?

What are iterator types in C++ and how do I use them?

Abstract art representing computer programming

Iterator types in C++ define how iterators access elements in a container. The most common types are:

  • Input Iterator: Read elements from a sequence.
  • Output Iterator: Write elements to a sequence.
  • Forward Iterator: Traverse a sequence in one direction.
  • Bidirectional Iterator: Traverse a sequence in both directions.
  • Random Access Iterator: Access any element in constant time.

In most cases, using auto for the return type of begin() and end() is sufficient. However, if you need to specify the type explicitly, you can use the iterator type provided by the container. Here's how to do it with std::vector:

#include <vector>
#include <string>

class Player {
public:
  Player(std::string Name) : mName(Name) {}
  std::string GetName() const { return mName; }
private:
  std::string mName;
};

class Party {
public:
  void AddMember(const std::string& NewMember) {
    PartyMembers.emplace_back(NewMember);
  }

  std::vector<Player>::iterator begin() {
    return PartyMembers.begin();
  }
  
  std::vector<Player>::iterator end() {
    return PartyMembers.end();
  }

private:
  std::vector<Player> PartyMembers;
};

int main() {
  Party MyParty;
  MyParty.AddMember("Legolas");
  MyParty.AddMember("Gimli");
  MyParty.AddMember("Frodo");

  for (const auto& Player : MyParty) {
    std::cout << Player.GetName() << '\n';
  }
}
Legolas
Gimli
Frodo
This Question is from the Lesson:

Implementing Ranges for Custom Types

Learn to implement iterators in custom types, and make them compatible with range-based techniques.

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

This Question is from the Lesson:

Implementing Ranges for Custom Types

Learn to implement iterators in custom types, and make them compatible with range-based techniques.

A computer programmer
Part of the course:

Professional C++

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

Free, unlimited access

This course includes:

  • 125 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
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