c++ - 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;
}
我假设我必须要求用户输入有多少个顶点和边,当用户输入边时,我会将它们一一放入数组中。
但是,我遇到了一个问题,即当未定义但输入了顶点数时,函数会说它未声明,依此类推。
有没有人知道最好的方法来做到这一点?
先感谢您!
解决方案
您可以用来收集可变数量数据的技术是首先询问用户他们需要多少个顶点,然后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
.
推荐阅读
- android - React Native Rich Editor:在android上调用setContentHTML后无法更改文本末尾的光标位置
- sql - 由于批量更新失败,PutSQL 更新数据库失败。如何解决?
- sql - 如何聚合列并计算 SQL 中的累积总和(R 中的 mutate() 和 cumsum())
- java - 片段中的访问工具栏
- ios - Unity IOS 崩溃
- postgresql - 如果存在则选择列,否则为空 - PSQL
- python - Python websocket上下文管理器,主体为真,关闭连接
- python - 有人可以解释为什么这段代码不能按我想要的方式工作吗?
- javascript - 创建切换/开关以显示不同的信息
- python-3.x - 当我将 Heroku Postgres 连接到 Heroku 时,我得到一个内部服务器错误