首页 > 解决方案 > C ++如何使用户能够输入将放置在多维数组中的值

问题描述

这可能是一个非常像初学者的问题。

但是,我有一个适用于图形的算法,而我目前拥有的只是预先输入的值。我想这样做,以便用户能够输入图形的边缘,并且将用这些值填充多维数组。

这是代码的一些位

#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;
}

我假设我必须要求用户输入有多少个顶点和边,当用户输入边时,我会将它们一一放入数组中。

但是,我遇到了一个问题,即当未定义但输入了顶点数时,函数会说它未声明,依此类推。

有没有人知道最好的方法来做到这一点?

先感谢您!

标签: c++multidimensional-arraygraphundefinedgraph-coloring

解决方案


您可以用来收集可变数量数据的技术是首先询问用户他们需要多少个顶点,然后std::cin循环for收集实际数据。

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);
}

我建议 astd::vector<bool>保存这些值,因为它是一个可变大小的数组。要像访问二维数组一样访问这个一维数组中的值,请使用表达式graph[y*vertex_count+x]

运行程序时,可以像这样输入数据:

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

因为std::cin分隔所有空格,而不仅仅是\n.


推荐阅读