【问题标题】:Creating a Dynamic 2D Array that has x y coordinates like a graph创建具有 x y 坐标的动态 2D 数组,如图形
【发布时间】:2019-06-14 20:03:58
【问题描述】:

在显示从左下角 (x,y) = (0,0) 开始的二维数组时需要帮助。

这是我到目前为止所拥有的,我无法将左下角设为 (0,0)。我有的是

x1y1,x1y2,x1y3,x1y4,x1y5,

x2y1,x2y2,x2y3,x2y4,x2y5,

x3y1,x3y2,x3y3,x3y4,x3y5,

x4y1,x4y2,x4y3,x4y4,x4y5,

x5y1,x5y2,x5y3,x5y4,x5y5,

我想拥有

x1y5,x2y5,x3y5,x4y5,x5y5,

x1y4,x2y4,x3y4,x4y4,x5y4,

x1y3,x2y3,x3y3,x4y3,x5y3,

x1y2,x2y2,x3y2,x4y2,x5y2,

x1y1,x2y1,x3y1,x4y1,x5y1,

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

string ** array2D = nullptr;

void init2DArray(int, int);
void populate2DArray (int, int);
void display2DArray (int, int);
void safelyDeallocateMemory (int, int);

int main() {
   int row, col;
   row = col = 0;
   cout << "Pls enter no. of cols : ";
   cin >> col;
   cout << endl;

   cout << "Pls enter no. of rows : ";
   cin >> row;
   cout << endl;

    init2DArray (col, row);
    populate2DArray (col, row);
    display2DArray (col, row);
    safelyDeallocateMemory (col, row);

    cout << endl;

  return 0;
 }

void init2DArray (int col, int row) {
        array2D = new string * [row];

        for (int i = 0; i < row; i++)
              array2D [i] = new string [col];
}

void populate2DArray (int col, int row) {
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {

                ostringstream oss;
                oss << "x" << i + 1 << "y" << j + 1;

                array2D [i][j] = oss.str();
             }
         }
  }

void display2DArray (int col, int row) {
        cout << endl;
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                cout << array2D [i][j] << ", ";
            }
            cout << endl;
        }
 }

【问题讨论】:

    标签: arrays c++11


    【解决方案1】:
    for (int i = 0; i < row; i++) {
       for (int j = 0; j < col; j++) {
    
         ostringstream oss;
         oss << "x" << j + 1 << "y" << (row - i);
    
         array2D [i][j] = oss.str();
       }
    }
    

    你应该做一些小事。将字符串推送到oss 时,您必须将j + 1 附加到x,因为首先执行内部循环。对于y,您只需将formula 更改为(row - i);由于i0 开始,您可以拥有5, 4, 3, 2, 1。如果row5,那么你有5-0 = 5,那么下一次迭代你有5-1 = 4 等等。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-27
      • 1970-01-01
      • 2019-05-14
      • 1970-01-01
      • 2023-04-01
      相关资源
      最近更新 更多