Skip to content

Commit 905d024

Browse files
Refactor test_node's neighbor management to use weak pointers and improve get_successors() for expired node handling
1 parent d52b1fc commit 905d024

File tree

1 file changed

+19
-3
lines changed

1 file changed

+19
-3
lines changed

tests/test_a_star.cpp

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,23 +4,39 @@
44
#include <memory>
55
#include <string>
66
#include <unordered_map>
7+
#include <vector>
78

89
class test_node final : public utils::node<int>
910
{
1011
public:
1112
test_node(std::string name, bool goal = false, int heuristic = 0) : id(std::move(name)), goal(goal), heuristic(heuristic) {}
1213

13-
void add_neighbor(const std::shared_ptr<test_node> &neighbor, int cost) { neighbors[neighbor] = cost; }
14+
void add_neighbor(const std::shared_ptr<test_node> &neighbor, int cost) { neighbors.emplace_back(neighbor, cost); }
1415

1516
[[nodiscard]] int cost(std::shared_ptr<utils::node<int>> = nullptr) const noexcept override { return heuristic; }
16-
[[nodiscard]] std::unordered_map<std::shared_ptr<utils::node<int>>, int> get_successors() override { return neighbors; }
17+
[[nodiscard]] std::unordered_map<std::shared_ptr<utils::node<int>>, int> get_successors() override
18+
{
19+
std::unordered_map<std::shared_ptr<utils::node<int>>, int> successors;
20+
successors.reserve(neighbors.size());
21+
22+
for (auto it = neighbors.begin(); it != neighbors.end();)
23+
if (auto locked = it->first.lock())
24+
{
25+
successors.emplace(std::move(locked), it->second);
26+
++it;
27+
}
28+
else
29+
it = neighbors.erase(it); // Drop edges to expired nodes.
30+
31+
return successors;
32+
}
1733
[[nodiscard]] bool is_goal() const noexcept override { return goal; }
1834

1935
private:
2036
std::string id;
2137
bool goal;
2238
int heuristic;
23-
std::unordered_map<std::shared_ptr<utils::node<int>>, int> neighbors;
39+
std::vector<std::pair<std::weak_ptr<utils::node<int>>, int>> neighbors;
2440
};
2541

2642
void test_finds_goal_with_shortest_path()

0 commit comments

Comments
 (0)