Implementing Ranges for Custom Types

How to create a custom collection with iterators in C++?

How do I create a custom collection with iterators in C++?

Abstract art representing computer programming

To create a custom collection with iterators in C++, you need to define your own collection class and provide begin() and end() methods.

These methods should return iterators that allow traversal of the collection. Here’s an example using a custom Party class:

#include <vector>
#include <string>
#include <iostream>

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);
  }

  auto begin() {
    return PartyMembers.begin();
  }
  auto 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

By defining these methods, you make your custom collection compatible with range-based for loops and other STL algorithms that require iterators.

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