How to use range-based for loops in C++?
How can I use range-based for loops with my custom types in C++?
To use range-based for loops with your custom types in C++, you need to implement begin()
and end()
methods that return iterators.
Once you have these methods in place, you can use the range-based for loop syntax to iterate over your collection. Here's an example:
#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 begin()
and end()
, your custom type Party
can be used in a range-based for loop to iterate over its elements.
Implementing Ranges for Custom Types
Learn to implement iterators in custom types, and make them compatible with range-based techniques.