diff --git a/lib/graph/graph.hpp b/lib/graph/graph.hpp index c06331e..6d2f75b 100644 --- a/lib/graph/graph.hpp +++ b/lib/graph/graph.hpp @@ -198,20 +198,18 @@ inline void Graph::modifyVertex(const_reference old_data, const_reference new if (old_data == new_data) return; - v_iterator it = m_vertices.find(old_data); - if (it == m_vertices.end()) - return; - std::vector neighbours = neighboursOf(old_data); for (auto &v : neighbours) { std::vector& n_v = nonConstNeighboursOf(v); typename std::vector::iterator n_it = std::find(n_v.begin(), n_v.end(), old_data); *n_it = new_data; } + const auto number_of_removed_elements = m_vertices.erase(old_data); - m_vertices.erase(it); - std::pair p(new_data, neighbours); - m_vertices.insert(p); + if (number_of_removed_elements > 0) { + std::pair p(new_data, neighbours); + m_vertices.insert(p); + } } template diff --git a/test/graph/test_graph.hpp b/test/graph/test_graph.hpp index 4f99470..c39da43 100644 --- a/test/graph/test_graph.hpp +++ b/test/graph/test_graph.hpp @@ -351,7 +351,7 @@ TEST_CASE( "Graph custom vertices", "[graph][data_structure]" ) { } -TEST_CASE( "Graph adding/removing", "[graph][data_structure]" ) { +TEST_CASE( "Graph adding/removing with more data", "[graph][data_structure]" ) { SECTION("Adding some edges") { Graph g = { {1, 2}, {1, 3}, {1, 4}, {2, 4}, {3, 4} }; @@ -445,6 +445,48 @@ TEST_CASE( "Graph adding/removing", "[graph][data_structure]" ) { REQUIRE( connected(g, 4, 2) == true ); REQUIRE( connected(g, 4, 3) == true ); } + + SECTION("Adding some edges, modifying 1 vertex") { + Graph g = { {1, 2}, {1, 3}, {1, 4}, {2, 4}, {3, 4} }; + REQUIRE( numberOfVertices(g) == 4 ); + REQUIRE( numberOfEdges(g) == 5*2 ); + + g.modifyVertex(1, 5); + REQUIRE( numberOfVertices(g) == 4 ); + REQUIRE( numberOfEdges(g) == 5*2 ); + REQUIRE( contains(g, 1) == false ); + REQUIRE( contains(g, 5) == true ); + + REQUIRE( connected(g, 1, 2) == false ); + REQUIRE( connected(g, 1, 3) == false ); + REQUIRE( connected(g, 1, 4) == false ); + REQUIRE( connected(g, 2, 1) == false ); + REQUIRE( connected(g, 2, 4) == true ); + REQUIRE( connected(g, 3, 1) == false ); + REQUIRE( connected(g, 3, 4) == true ); + REQUIRE( connected(g, 4, 1) == false ); + REQUIRE( connected(g, 4, 2) == true ); + REQUIRE( connected(g, 4, 3) == true ); + + REQUIRE( connected(g, 5, 2) == true ); + REQUIRE( connected(g, 5, 3) == true ); + REQUIRE( connected(g, 5, 4) == true ); + REQUIRE( connected(g, 2, 5) == true ); + REQUIRE( connected(g, 3, 5) == true ); + REQUIRE( connected(g, 4, 5) == true ); + } + + SECTION("Adding some edges, modifying 1 unexisting vertex") { + Graph g = { {1, 2}, {1, 3}, {1, 4}, {2, 4}, {3, 4} }; + REQUIRE( numberOfVertices(g) == 4 ); + REQUIRE( numberOfEdges(g) == 5*2 ); + + g.modifyVertex(5, 6); + REQUIRE( numberOfVertices(g) == 4 ); + REQUIRE( numberOfEdges(g) == 5*2 ); + REQUIRE( contains(g, 5) == false ); + REQUIRE( contains(g, 6) == false ); + } }