Medium
Appending to a playlist mid-traversal
What does this program print?
main.cpp
struct Song { std::string title; };
class Playlist {
public:
class Iterator {
public:
Iterator(const Playlist* pl, std::size_t i) : pl_(pl), i_(i) {}
const Song& operator*() const { return pl_->songs_[i_]; }
Iterator& operator++() { ++i_; return *this; }
bool operator!=(const Iterator& o) const { return i_ != o.i_; }
private:
const Playlist* pl_;
std::size_t i_;
};
void add(std::string t) { songs_.push_back({std::move(t)}); }
Iterator begin() const { return {this, 0}; }
Iterator end() const { return {this, songs_.size()}; }
private:
std::vector<Song> songs_;
};
int main() {
Playlist pl;
pl.add("intro");
pl.add("encore");
pl.add("outro");
for (const Song& s : pl) {
std::cout << s.title << "\n";
if (s.title == "encore") pl.add("bonus"); // may reallocate songs_
}
}31 of 44 in Design Patterns