简体   繁体   中英

How to implement add_vertex and add_edge function in a graph?

I'm creating a templated graph data structure in C++ and I'm working on the functions add_vertex and add_edge.

For the add_vertex function, I tried using adjacency matrix and set it to false. However, I'm not sure if I did it correctly.

Here is a snippet of the code:

template<typename vertex>
class directed_graph
{
    private:
            std::vector<std::vector<bool> > adj_matrix;
            size_t size;
            int num_of_vertices;

    public:
            void add_vertex(const vertex&); 
            void add_edge(const vertex&, const vertex&); 
}


template <typename vertex> 
void directed_graph<vertex>::add_vertex(const vertex& u) 
{
int newVertexNumber = num_of_vertices;
num_of_vertices++;

for(int i = 0; i<num_of_vertices; i++)
{
    adj_matrix[i][newVertexNumber] = false;
    adj_matrix[newVertexNumber][i] = false;
}

newVertexNumber = u;

}


template <typename vertex>
void directed_graph<vertex>::add_edge(const vertex& u, const vertex& v) 
{
 if ((u >= 0) && (u < size) && (v >= 0) && (v < size) && (u != v))
     {
    adj_matrix[u][v] = true;        
    adj_matrix[v][u] = true;
 }
}

for the method parameters like "const vertex& u" im not too sure if its is possible to pass the vertex type to the index in adj_matrix[][]. So, i think i need some kind of method to extract the index(position) of u and v in the matrix then pass the index to adj_matrix[index_u][index_v], but im not sure how. Please help, thank you.

When adding a new vertex the matix size must change too, std::vector doesn't resize automatically on write.

// Extend the matrix
int n = adj_matrix.size();
adj_matrix.resize(n+1);          // Add one more row
for (auto& row : adj_matrix) {
    row.resize(n+1);             // Add one more column to each row
}

Note that new elements in vectors of bool are automatically initialized to false unless explicitly told to use true .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM