You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
41 lines
699 B
C++
41 lines
699 B
C++
#pragma once
|
|
#include <stack>
|
|
|
|
#include "iterators/BaseIterator.h"
|
|
|
|
template <typename T>
|
|
class BFSIterator : public BaseIterator<T> {
|
|
public:
|
|
explicit BFSIterator(T* ptr) : BaseIterator<T>(ptr) {
|
|
if (!this->current())
|
|
return;
|
|
|
|
for (auto& it : this->current()->children())
|
|
q.push({it.get(), 1});
|
|
}
|
|
|
|
IIterator<T>& operator++() override {
|
|
advance();
|
|
return *this;
|
|
}
|
|
|
|
protected:
|
|
std::queue<std::pair<T*, size_t>> q;
|
|
|
|
void advance() {
|
|
if (q.empty()) {
|
|
this->set_current(nullptr);
|
|
return;
|
|
}
|
|
|
|
auto& [node, lvl] = q.front();
|
|
q.pop();
|
|
|
|
this->set_current(node);
|
|
this->set_level(lvl);
|
|
|
|
for (auto& it : this->current()->children())
|
|
q.push({it.get(), lvl + 1});
|
|
}
|
|
};
|