首页 > 解决方案 > 如何使用循环一次显示所有循环信息?功能问题

问题描述

我正在学习 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";
}

电流输出:

如您所见,每个“城市坐标”都有一个单独的网格

标签: c++loopsrandomgridcoordinates

解决方案


您需要存储所有城市坐标,以便在单个网格打印上显示它们。在下面的代码中,我更改了一些内容以希望解决您的问题。

  • 我已将所有与城市相关的数据移动到一个结构中
  • 然后在网格输出之前初始化所有城市
  • 打印网格时,我们必须搜索所有城市,如果它们的坐标与当前位置匹配,则打印相应的索引。

现场演示

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

推荐阅读