CS代考 General Directed Weighted Graph

General Directed Weighted Graph

1 Change Log

Copyright By PowCoder代写 加微信 powcoder

2 The Task
2.1 Definitions [gdwg.definitions]
2.2 Constructors [gdwg.ctor]
2.3 Modifiers [gdwg.modifiers]
2.4 Accessors [gdwg.accessors]
2.5 Iterator access [gdwg.iterator.access]
2.6 Comparisons [gdwg.cmp]
2.7 Extractor [gdwg.io]
2.8 Iterator [gdwg.iterator]
2.8.1 Iterator constructor [gdwg.iterator.ctor]
2.8.2 Iterator source [gdwg.iterator.source]
2.8.3 Iterator traversal [gdwg.iterator.traversal]
2.8.4 Iterator comparison [gdwg.iterator.comparison]

2.9 Compulsory internal representation [gdwg.internal]
2.9.1 But why smart pointers [gdwg.internal.rationale]

2.10 Other notes [other.notes]
2.10.1 const-correctness [const.correctness]
2.10.2 Member types [gdwg.types]

3 Getting Started
3.1 Running your tests
3.2 Adding more tests

4 Marking Criteria
5 Originality of Work
6 Submission
7 Late Submission Policy

1 Change Log

– **2022-07-10**: Initial Release

2 The Task

Write a graph library type in C++, in include/gdwg/graph.hpp.

In this assignment, you will write a generic directed weighted graph (GDWG) with value-semantics in C++. Both the data stored at a node and the weight stored at an edge will be parameterised types. The types may be different. For example, here is a graph with nodes storing std::string and edges weighted by int:

using graph = gdwg::graph;

Formally, this directed weighted graph G = (N, E) will consist of a set of nodes N and a set of weighted edges E.

All nodes are unique, that is to say, no two nodes will have the same value and shall not compare equal using operator==.

Given a node, an edge directed into it is called an incoming edge and an edge directed out of it is called an outgoing edge. The in-degree of a node is the number of its incoming edges. Similarly, the out-degree of a node is the number of its outgoing edges. Given a directed edge from src to dst, src is the source node and dst is known as the destination node.

Edges can be reflexive, that is to say, the source and destination nodes of an edge could be the same.

G is a multi-edged graph, as there may be two edges from the same source node to the same destination node with two different weights. Two edges from the same source node to the same destination node cannot have the same weight.

2.1 Definitions [gdwg.definitions]

Some words have special meaning in this document. This section precisicely defines those words.

Preconditions: the conditions that the function assumes to hold whenever it is called; violation of any preconditions results in undefined
Effects: the actions performed by the function.
Postconditions: the conditions (sometimes termed observable results) established by the function.
Returns: a description of the value(s) returned by the function.
Throws: any exceptions thrown by the function, and the conditions that would cause the exception.
Complexity: the time and/or space complexity of the function.
Remarks: additional semantic constraints on the function.
Unspecified: the implementation is allowed to make its own decisions regarding what is unspecified, provided that it still follows the explicitly specified wording.

An Effects element may specify semantics for a function F in code using the term Equivalent to. The semantics for F are interpreted as follows:

All of the above terminology applies to the provided code, whether or not it is explicitly specified. [Example: If F has a Preconditions element, but the code block doesn’t explicitly check them, then it is implied that the preconditions have been checked. —end example]
If there is not a Returns element, and F has a non-void return type, all the return statements are in the code block.
Throws, Postconditions, and Complexity elements always have priority over the code block.

Specified complexity requirements are upper bounds, and implementations that provide better complexity guarantees meet the requirements.

The class synopsis is the minimum text your header requires to compile most tests (this doesn’t mean that it will necessarily link or run as expected).

Blue text in code will link to C++ Reference or to another part of this document.

This section makes use of [stable.names]. A stable name is a short name for a (sub)section, and isn’t supposed to change. We will use these to reference specific sections of the document. [Example:

Student: Do we need to define gdwg::graph::operator!=?

Tutor: [other.notes] mentions that you don’t need to so you can get used to C++20’s generated operators.

—end example]

2.2 Constructors [gdwg.ctor]

It’s very important your constructors work. If we can’t validly construct your objects, we can’t test any of your other functions.

Effects: Value initialises all members.

Throws: Nothing.

graph(std::initializer_list il);

Effects: Equivalent to: graph(il.begin(), il.end());

template
graph(InputIt first, InputIt last);

Preconditions: Type InputIt models Cpp17InputIterator and is indirectly readable as type N.
Effects: Initialises the graph’s node collection with the range [first, last).

graph(graph&& other) noexcept;

Postconditions:

*this is equal to the value other had before this constructor’s invocation.
other.empty() is true.
All iterators pointing to elements owned by *this prior to this constructor’s invocation are invalidated.
All iterators pointing to elements owned by other prior to this constructor’s invocation remain valid, but now point to the elements owned by *this.

auto operator=(graph&& other) noexcept -> graph&;

Effects: All existing nodes and edges are either move-assigned to, or are destroyed.
Postconditions:

*this is equal to the value other had before this operator’s invocation.
other.empty() is true.
All iterators pointing to elements owned by *this prior to this operator’s invocation are invalidated.
All iterators pointing to elements owned by other prior to this operator’s invocation remain valid, but now point to the elements owned by *this.

Returns: *this.

graph(graph const& other);

Postconditions: *this == other is true.

auto operator=(graph const& other) -> graph&;

Postconditions:

*this == other is true.
All iterators pointing to elements owned by *this prior to this operator’s invocation are invalidated.

Returns: *this.

2.3 Modifiers [gdwg.modifiers]

auto insert_node(N const& value) -> bool;

Effects: Adds a new node with value value to the graph if, and only if, there is no node equivalent to value already stored.

Postconditions: All iterators are invalidated.

Returns: true if the node is added to the graph and false otherwise.

auto insert_edge(N const& src, N const& dst, E const& weight) -> bool;

Effects: Adds a new edge representing src → dst with weight weight, if, and only if, there is no edge equivalent to value_type{src, dst, weight} already stored. [Note:⁠ Nodes are allowed to be connected to themselves. —end note]

Postconditions: All iterators are invalidated.

Returns: true if the node is added to the graph and false otherwise.

Throws: std::runtime_error(“Cannot call gdwg::graph::insert_edge when either src or dst node does not exist”) if either of is_node(src) or is_node(dst) are false. [Note: Unlike Assignment 2, the exception message must be used verbatim. —end note]

auto replace_node(N const& old_data, N const& new_data) -> bool;

Effects: Replaces the original data, old_data, stored at this particular node by the replacement data, new_data. Does nothing if new_data already exists as a node.

Postconditions: All iterators are invalidated.

Returns: false if a node that contains value new_data already exists and true otherwise.

Throws: std::runtime_error(“Cannot call gdwg::graph::replace_node on a node that doesn’t exist”) if is_node(old_data) is false. [Note: Unlike Assignment 2, the exception message must be used verbatim. —end note]

auto merge_replace_node(N const& old_data, N const& new_data) -> void;

Effects: The node equivalent to old_data in the graph are replaced with instances of new_data. After completing, every incoming and outgoing edge of old_data becomes an incoming/ougoing edge of new_data, except that duplicate edges shall be removed.

Postconditions: All iterators are invalidated.

Throws: std::runtime_error(“Cannot call gdwg::graph::merge_replace_node on old or new data if they don’t exist in the graph”) if either of is_node(old_data) or is_node(new_data) are false. [Note: Unlike Assignment 2, the exception message must be used verbatim. —end note]

[Note: The following examples use the format (Nsrc, Ndst, E). [Example: Basic example.

Operation: merge_replace_node(A, B)
Graph before: (A, B, 1), (A, C, 2), (A, D, 3)
Graph after : (B, B, 1), (B, C, 2), (B, D, 3)

—end example][Example: Duplicate edge removed example.

Operation: merge_replace_node(A, B)
Graph before: (A, B, 1), (A, C, 2), (A, D, 3), (B, B, 1)
Graph after : (B, B, 1), (B, C, 2), (B, D, 3)

—end example][Example: Diagrammatic example.

—end example] —end note]

auto erase_node(N const& value) -> bool;

Effects: Erases all nodes equivalent to value, including all incoming and outgoing edges.

Returns: true if value was removed; false otherwise.

Postconditions: All iterators are invalidated.

auto erase_edge(N const& src, N const& dst, E const& weight) -> bool;

Effects: Erases an edge representing src → dst with weight weight.

Returns: true if an edge was removed; false otherwise.

Postconditions: All iterators are invalidated.

Throws: std::runtime_error(“Cannot call gdwg::graph::erase_edge on src or dst if they don’t exist in the graph”) if either is_node(src) or is_node(dst) is false. [Note: Unlike Assignment 2, the exception message must be used verbatim. —end note]

Complexity: O(log (n) + e), where n is the total number of stored nodes and e is the total number of stored edges.

auto erase_edge(iterator i) -> iterator;

Effects: Erases the edge pointed to by i.

Complexity: Amortised constant time.

Returns: An iterator pointing to the element immediately after i prior to the element being erased. If no such element exists, returns end().

Postconditions: All iterators are invalidated. [Note: The postcondition is slightly stricter than a real-world container to help make the assingment easier (i.e. we won’t be testing any iterators post-erasure). —end note]

auto erase_edge(iterator i, iterator s) -> iterator;

Effects: Erases all edges between the iterators [i, s).

Complexity O(d), where d=std::distance(i, s).

Returns: An iterator equivalent to s prior to the items iterated through being erased. If no such element exists, returns end().

Postconditions: All iterators are invalidated. [Note: The postcondition is slightly stricter than a real-world container to help make the assingment easier (i.e. we won’t be testing any iterators post-erasure). —end note]

auto clear() noexcept -> void;

Effects: Erases all nodes from the graph.

Postconditions: empty() is true.

2.4 Accessors [gdwg.accessors]

[[nodiscard]] auto is_node(N const& value) -> bool;

Returns: true if a node equivalent to value exists in the graph, and false otherwise.

Complexity: O(log (n)) time.

[[nodiscard]] auto empty() -> bool;

Returns: true if there are no nodes in the graph, and false otherwise.

[[nodiscard]] auto is_connected(N const& src, N const& dst) -> bool;

Returns: true if an edge src → dst exists in the graph, and false otherwise.

Throws: std::runtime_error(“Cannot call gdwg::graph::is_connected if src or dst node don’t exist in the graph”) if either of is_node(src) or is_node(dst) are false. [Note: Unlike Assignment 2, the exception message must be used verbatim. —end note]

[[nodiscard]] auto nodes() -> std::vector;

Returns: A sequence of all stored nodes, sorted in ascending order.

Complexity: O(n), where n is the number of stored nodes.

[[nodiscard]] auto weights(N const& src, N const& dst) -> std::vector;

Returns: A sequence of weights from src to dst, sorted in ascending order.

Complexity: O(log (n) + e), where n is the number of stored nodes and e is the number of stored edges.

Throws: std::runtime_error(“Cannot call gdwg::graph::weights if src or dst node don’t exist in the graph”) if either of is_node(src) or is_node(dst) are false. [Note: Unlike Assignment 2, the exception message must be used verbatim. —end note]

[[nodiscard]] auto find(N const& src, N const& dst, E const& weight) -> iterator;

Returns: An iterator pointing to an edge equivalent to value_type{src, dst, weight}, or end() if no such edge exists.

Complexity: O(log (n) + log (e)), where n is the number of stored nodes and e is the number of stored edges.

[[nodiscard]] auto connections(N const& src) -> std::vector;

Returns: A sequence of nodes (found from any immediate outgoing edge) connected to src, sorted in ascending order, with respect to the connected nodes.

Complexity: O(log (n) + e), where e is the number of outgoing edges associated with src.

Throws: std::runtime_error(“Cannot call gdwg::graph::connections if src doesn’t exist in the graph”) if is_node(src) is false. [Note: Unlike Assignment 2, the exception message must be used verbatim. —end note]

2.5 Iterator access [gdwg.iterator.access]

[[nodiscard]] auto begin() const -> iterator;

Returns: An iterator pointing to the first element in the container.

[[nodiscard]] auto end() const -> iterator;

Returns: An iterator denoting the end of the iterable list that begin() points to.

Remarks: [begin(), end()) shall denote a valid iterable list.

2.6 Comparisons [gdwg.cmp]

[[nodiscard]] auto operator==(graph const& other) -> bool;

Returns: true if *this and other contain exactly the same nodes and edges, and false otherwise.

Complexity: O(n + e) where n is the sum of stored nodes in *this and other, and e is the sum of stored edges in *this and other.

2.7 Extractor [gdwg.io]

friend auto operator<<(std::ostream& os, graph const& g) -> std::ostream&;

Effects: Behaves as a formatted output function of os.

Returns: os.

Remarks: The format is specified thusly:

[source_node1] [edges1]
[source_node2] [edges2]
[source_noden] [edgesn]

[source_node1], …, [source_noden] are placeholders for all nodes that the graph stores, sorted in ascending order. [edges1], …, [edgesn] are placeholders for

[noden_connected_node1] | [weight]
[noden_connected_node2] | [weight]
[noden_connected_noden] | [weight]

where [noden_conencted_node1] | [weight], …, [noden_connected_noden] | [weight] are placeholders for each node’s connections and corresponding weight, also sorted in ascending order. [Note: If a node doesn’t have any connections, then its corresponding [edgesn] should be a line-separated pair of parentheses —end note]

using graph = gdwg::graph;
auto const v = std::vector{
{4, 1, -4},
{3, 2, 2},
{2, 4, 2},
{2, 1, 1},
{6, 2, 5},
{6, 3, 10},
{1, 5, -1},
{3, 6, -8},
{4, 5, 3},
{5, 2, 7},

auto g = graph{};
for (const auto& [from, to, weight] : v) {
g.insert_node(from);
g.insert_node(to);
g.insert_edge(from, to, weight)

g.insert_node(64);
auto out = std::ostringstream{};
auto const expected_output = std::string_view(R”(1 (
CHECK(out.str() == expected_output);

—end example ]

2.8 Iterator [gdwg.iterator]

template
class graph::iterator {
using value_type = graph::value_type;
using reference = value_type;
using pointer = void;
using difference_type = std::ptrdiff_t;
using iterator_category = std::bidirectional_iterator_tag;

// Iterator constructor
iterator() = default;

// Iterator source
auto operator*() -> reference;

// Iterator traversal
auto operator++() -> iterator&;
auto operator++(int) -> iterator;
auto operator–() -> iterator&;
auto operator–(int) -> iterator;

// Iterator comparison
auto operator==(iterator const& other) -> bool;
explicit iterator(unspecified);

Elements are lexicographically ordered by their source node, destination node, and edge weight, in ascending order.

Nodes without any connections are not traversed.

[Note: gdwg::graph::iterator models std::bidirectional_iterator. —end note]

2.8.1 Iterator constructor [gdwg.iterator.ctor]

iterator();

Effects: Value-initialises all members.

Remarks: Pursuant to the requirements of std::forward_iterator, two value-initialised iterators shall compare equal.

explicit iterator(unspecified);

Effects: Constructs an iterator to a specific element in the graph.

Remarks: There may be multiple constructors with a non-zero number of parameters.

2.8.2 Iterator source [gdwg.iterator.source]

auto operator*() -> reference;

Effects: Returns the current from, to, and weight.

2.8.3 Iterator traversal [gdwg.iterator.traversal]

auto operator++() -> iterator&;

Effects: Advances *this to the next element in the iterable list.

[Example: In this way, your iterator will iterator through a graph like the one below producing the following tuple values when deferenced each time:

gdwg::graph

(1, 12, 3)
(1, 21, 12)
(7, 21, 13)
(12, 19, 16)
(14, 14, 0)
(19, 1, 3)
(19, 21, 2)
(21, 14, 23)
(21, 31, 14)

—end example]

Returns: *this.

auto operator++(int) -> iterator;

Effects: Equivalent to:

auto temp = *this;
return temp;

auto operator–() -> iterator&;

Effects: Advances *this to the previous element in the iterable list.

Returns: *this.

auto operator–(int) -> iterator;

Effects: Equivalent to:

auto temp = *this;
return temp;

2.8.4 Iterator comparison [gdwg.iterator.comparison]

auto operator==(iterator const& other) -> bool;

Returns: true if *this and other are pointing to the same elements in the same iterable list, and false otherwise.

2.9 Compulsory internal representation [gdwg.internal]

Your graph is required to own the resources (nodes and edge weights) that are passed in through the insert functions. This means creating memory on the heap and doing a proper copy of the values from the caller. This is because resources in your graph should outlive the caller’s resouce that was passed in in case it goes out of scope. For example, we want the following code to be valid.

auto main() -> int {
gdwg::graph g;
std::string s1{“Hello”};
g.insert_node(s1);

// Even though s1 has gone out of scope, g has its own
// copied resource that it has stored, so the node
// will still be in here.
std::cout << g.is_node("Hello") << "\n"; // prints 'true'; Your graph is required to use smart pointers (however you please) to solve this problem. For each node, you are only allowed to have one underlying resource (heap) stored in your graph for it. This means every N can only be stored once per graph instance. For each edge, you should avoid not using unnecessary additional memory wherever possible. [Hint: In your own implementation you’re likely to use some containers to store things, and depending on your implementation choice, somewhere in those containers you’ll likely use either std::unique_ptr or std::shared_ptr —end hint]

2.9.1 But why smart pointers [gdwg.internal.rationale]

You could feasibly implement the assignment without any smart pointers, through lots of redundant copying. For example, having a massive data structure like:

std::map>>

You can see that in this structure you would have duplicates of nodes when trying to represent this complex structure. This takes up a lot of space. We want you to build a space efficient graph.

2.10 Other notes [other.notes]

Include a header guard in include/gdwg/graph.hpp

程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com