c++ - 如何使用循环一次显示所有循环信息?功能问题
问题描述
我正在学习 C++,希望对下面代码的功能有所帮助。我的代码的快速摘要/用法:程序是显示随机(x,y)坐标,然后在网格中打印出坐标。
我得到了关于随机化(x,y)坐标然后显示它们的网格位置的一切工作。
我遇到的问题是我的代码为每个坐标显示一个单独的网格,而不是在同一个网格上显示所有坐标。[我在下面附上了我当前输出的图片]。
我知道这是一个功能问题..但是我无法考虑如何操作我的循环以便首先显示坐标,然后是一个带有所有坐标的网格......我希望这是有道理的。
我的代码片段:
//Note: value of n and k is given by user earlier in the code
vector<vector<int> > vec( n , vector<int> (n));
cout << "\nGrid with city locations:\n";
for(i=0; i<k; i++) {
//random select int coordinates (x,y) for each K(cities)
x = rand() % n + 0;
y = rand() % n + 0;
arrCity[i] = i;
//display coordinates for city 1..city2.. etc
cout << "City " << arrCity[i] <<": (" << x << "," << y << ")" << endl;
//display cities on grid
for (int rows=0; rows < n; rows++) {
for (int columns=0; columns < n; columns++) {
if ((rows == y) && (columns == x)) {
cout << "|" << (i);
} else {
cout << "|_";
}
}
cout << "\n";
}
cout << "\n";
}
电流输出:
如您所见,每个“城市坐标”都有一个单独的网格
解决方案
您需要存储所有城市坐标,以便在单个网格打印上显示它们。在下面的代码中,我更改了一些内容以希望解决您的问题。
- 我已将所有与城市相关的数据移动到一个结构中
- 然后在网格输出之前初始化所有城市
- 打印网格时,我们必须搜索所有城市,如果它们的坐标与当前位置匹配,则打印相应的索引。
#include <vector>
#include <iostream>
struct City
{
int index;
int x, y;
City(int index_, int x_, int y_)
: index(index_), x(x_), y(y_)
{ }
};
int main()
{
int n = 10;
int k = 6;
std::vector<City> arrCity;
arrCity.reserve(k);
for(int i = 0; i < k; i++)
arrCity.emplace_back(i, rand() % n, rand() % n);
std::cout << "\nGrid with city locations:\n";
for (int k = 0; k < arrCity.size(); k++)
std::cout << "City " << arrCity[k].index << ": (" << arrCity[k].x << "," << arrCity[k].y << ")" << std::endl;
//display cities on grid
for (int i=0; i < n; i++) {
for (int j=0; j < n; j++) {
int w = -1;
for (int k = 0; k < arrCity.size(); k++)
if ((i == arrCity[k].y) && (j == arrCity[k].x))
w = k;
if (w >= 0)
std::cout << "|" << arrCity[w].index;
else
std::cout << "|_";
}
std::cout << "\n";
}
return 0;
}
推荐阅读
- javascript - 如何使用jQuery取消选中所有单击复选框,除了单击一个
- powerbi - Power-BI:在数据区添加列或在 Power-Query 中添加列
- python - 基于多列的 Python 合并
- javascript - Javascript 在 catch 块中丢失了回溯
- widget - Databricks:在查询中调用小部件值
- visual-studio - 限制多值参数选择 SSRS 的数量
- airflow - 如果工作人员本身出现故障,在 Celery 工作人员上运行的气流传感器会发生什么情况
- three.js - AR.js aframe 对象显示也没有指向标记
- php - 如何使用 PHPmailer 发送参数以在 cid 内部进行跟踪
- sql - Rewrite Join 引入了没有 DISTINCT 的重复行