To implement iterators for custom types in C++, you need to define begin()
and end()
methods in your class.
These methods should return iterators that can traverse the elements of your collection. Here's an example using a class Party
that contains a collection of Player
objects managed by an std::vector
.
#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
Answers to questions are automatically generated and may not have been reviewed.
Learn to implement iterators in custom types, and make them compatible with range-based techniques.