Skip to content

Commit

Permalink
Optimized: change comparator to generics
Browse files Browse the repository at this point in the history
  • Loading branch information
huanmie committed Jul 24, 2022
1 parent acf78d5 commit 97c0c44
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 6 deletions.
11 changes: 6 additions & 5 deletions Graph/Graph.h
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@ class Graph
public:
using PathType = std::unordered_map<Vertex, Weight>::value_type;
using ResultsType = std::vector<std::reference_wrapper<const PathType>>;
using ComparatorType = bool(*)(const Weight&, const Weight&);
using BestPathType = std::variant<std::string, ResultsType>(const Graph<Vertex, Weight>*, const Vertex&, const Vertex&, ComparatorType);
using BestPathType = std::variant<std::string, ResultsType>(const Graph<Vertex, Weight>*, const Vertex&, const Vertex&, std::function<bool(const Weight&, const Weight&)>&&);

private:
template<typename T>
Expand Down Expand Up @@ -39,7 +38,6 @@ class Graph
AdjacencyMatrix matrix;
mutable std::unordered_map<Vertex, Weight> cache;
std::function<BestPathType> best_path;
static constexpr ComparatorType less = [](const Weight& first, const Weight& second) {return first < second; };

public:
static Weight INFINITE;
Expand Down Expand Up @@ -120,10 +118,13 @@ class Graph
best_path = std::forward<decltype(function)>(function);
}

std::variant<std::string, ResultsType> GetBestPath(const Vertex& begin, const Vertex& end, ComparatorType comparator = less) const
// Do not pass std::function to comparator
template<std::invocable<const Weight&, const Weight&> T = std::less<void>>
requires (std::is_pointer_v<T> || (std::is_object_v<T> && std::is_empty_v<T>)) && std::is_same_v<std::invoke_result_t<T, const Weight&, const Weight&>, bool>
std::variant<std::string, ResultsType> GetBestPath(const Vertex& begin, const Vertex& end, T comparator = T{}) const
{
if (best_path)
return best_path(this, begin, end, comparator);
return best_path(this, begin, end, std::function<bool(const Weight&, const Weight&)>{ comparator });
else if constexpr (requires (Weight a, Weight b) { a < b; a -= b; })
{
if (Weight{} + Weight{} != Weight{})
Expand Down
2 changes: 1 addition & 1 deletion Graph/Performance.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ int main()
{
elapse e;
for (size_t i = 0; i < test_set.size() / 2; i++)
graph.GetBestPath(test_set[i * 2], test_set[i * 2 + 1], [](const int& first, const int& second) {return first > second; });
graph.GetBestPath(test_set[i * 2], test_set[i * 2 + 1], std::greater<void>{});
}
return 0;
}

0 comments on commit 97c0c44

Please sign in to comment.