二维数组和坐标

时间:2017-01-25 18:46:00

标签: c++ c++11

我试图在我的"画布中打印空间" (例如坐标(2,2))通过在控制台窗口中编辑由█块制作的80x20网格。

  • 请首先建议我更好的方法来创建网格 (我刚刚学会了 - 每个循环)

  • 为什么我在运行程序后会得到这3个字符?

  • 为什么不在(2,2)区块上的空间,但显然是在中间某个位置的第一行?

enter image description here

代码:

#include <iostream>

int main()
{
 uint8_t block {219}; // █
 uint8_t space {32};  // ' '

 uint8_t screen[80][20] {};

 for (auto &row : screen)   // make the "canvas"
    for (auto &col : row)
        col = block;

 for (int row = 1; row <= 80; ++row)
 {
    for (int col = 1; col <= 20; ++col)
    {
        if (col == 2 && row == 2)
            screen[row][col] = space;

    }
 }


std::cout << *screen;

return 0;
}

1 个答案:

答案 0 :(得分:2)

一些问题:

  • C ++使用基于0的索引。你想要for (int row = 0; row < 80; ++row)
  • 您正在遍历整个数组只是为了添加空格,为什么不使用screen[2][2]=space
  • 您正在将整个阵列打印到屏幕上,但该阵列不包含换行符,因此您依靠控制台进行换行,这是一个安全的假设吗?
  • 您的字符串不包含必需的null-termination,因此会打印额外的字符。
  • 您已将数组命名为column-major。我怀疑你会想要使用row-major。

由于您使用的是C ++,我可能会编写如下代码:

#include <iostream>
#include <vector>

class Screen {
 public:
  typedef uint8_t schar;
  std::vector<schar> data; //Store data in a flat array: increases speed by improving caching
  int width;
  int height;
  Screen(int width, int height, schar initchar){
    this->width = width;     //'this' refers to the current instantiation of this object
    this->height = height;
    data.resize(width*height,initchar); //Resize vector and set its values
  }
  schar& operator()(int x, int y){
    return data[y*width+x];
  }
  void setAll(schar initchar){
    std::fill(data.begin(),data.end(),initchar);
  }
  void print() const {
    std::cout<<"\033[2J"; //ANSI command: clears the screen, moves cursor to upper left
    for(int y=0;y<height;y++){
      for(int x=0;x<width;x++)
        std::cout<<data[y*width+x];
      std::cout<<"\n";     //Much faster than std::endl
    }
    std::cout<<std::flush; //Needed to guarantee screen displays
  }
};

int main(){
  const int WIDTH  = 80;
  const int HEIGHT = 20;

  uint8_t block {219}; // █
  uint8_t space {32};  // ' '

  Screen screen(WIDTH,HEIGHT,block);
  screen(2,2) = space;
  screen.print();

  return 0;
}