c++multidimensional-arraygraphundefinedgraph-coloring

C++ How to enable a user to enter the values which would be placed in multidimensional arrray


this is probably a very beginner-like question.

However, I have an algorithm that works with graphs, and what I currently have is just the pre-entered values. I want to make it so a user would be able to enter the edges of the graph and a multidimensional array would be filled up with the values.

Here are some bits of the code

#include <stdbool.h>
#include <stdio.h>
#include <iostream>
using namespace std;

#define vertex_count 4
int main()
{

   // int vertex_count;

    bool graph[vertex_count][vertex_count] =
    {
        { 0, 1, 1, 1 },
        { 1, 0, 1, 0 },
        { 1, 1, 0, 1 },
        { 1, 0, 1, 0 },
    };
    int used_colors = 3;
    graphColor(graph, used_colors);

    return 0;
}

I am assuming that I would have to ask the user to enter how many vertices and edges there are and when the user enters the edges, I would be putting them in the array one by one.

However, I run into a problem that when the vertex count is not defined but is entered, functions say that it is not declared, and so on.

Does anyone have an idea on the best way to do this?

Thank you in advance!


Solution

  • A technique you could use to collect a variable amount of data would be to first ask the user how many vertices they require, and then std::cin in a for loop to collect the actual data.

    std::vector<bool> graph;
    int vertex_count = 0;
    std::cout << "How many vertices?\n";
    std::cin >> vertex_count;
    std::cout << "Enter the graph:\n";
    int answer = 0;
    for (int i = 0; i < vertex_count * vertex_count; ++i) {
        std::cin >> answer;
        graph.push_back(answer);
    }
    

    I recommend a std::vector<bool> to hold the values because it is a variable sized array. To access values in this one dimensional array as though it were two dimensional, use the expression graph[y*vertex_count+x].

    When running the program, the data can be entered like:

    How many vertices?
    4
    Enter the graph:
    1 0 1 0
    1 1 0 1
    0 0 0 0
    1 1 0 0
    

    because std::cin deliminates on all whitespace, not just \n.