简体   繁体   English

如何用从负数到正数的单元格组成数组?

[英]How to make array with cells numbered from negative number to positive?

I'd like to make non-graphic (text) C++ game (you move your character using n, s, w, e and every location is described). 我想制作非图形(文字)C ++游戏(您使用n,s,w,e移动角色,并描述了每个位置)。 Locations will be an array of an objects (there will be location description and other information in this array). 位置将是一个对象数组(此数组中将包含位置说明和其他信息)。 I've started making this game, but I have a question: Is it possible to make arrays with dimensions x - from -100 to 100 and z - from -100 to 100? 我已经开始制作这个游戏了,但是我有一个问题:是否可以制作尺寸为x-从-100到100和z-从-100到100的数组? If it is not possible, are there other ways to do it? 如果不可能,还有其他方法可以做到吗? (I don't want a [0][0] position in one of 4 corners, but on the middle.) (我不希望[0] [0]的位置位于4个角之一,而是位于中间)。

An Array can have only positive indexes: 数组只能具有正索引:

Location loc[201][201];

define a Funktion that returns your desired Location: 定义一个返回所需位置的功能:

Location getLocation(int xCoord, int yCoord)
{
  if (abs(x)>100 || abs(y)>100)
    throw std::invalid_argument( "value out of range"); 
  return loc[xCoord+100][yCoord+100];
}

Then you can get the Location by calling the function getLocation(x,y) 然后,您可以通过调用函数getLocation(x,y)来获取位置

One common (but rather sketchy) method is to do something like this (example for 21 x 21 board): 一种常见(但相当粗略)的方法是执行以下操作(例如21 x 21电路板):

#include <iostream>

using namespace std;

int main()
{
    typedef int (*board_ptr)[21];

    int board_data[21][21];
    board_ptr board = (board_ptr)&board_data[10][10];

    for (int i = -10; i <= 10; ++i)
        for (int j = -10; j <= 10; ++j)
            board[i][j] = 0;
    board[-10][-10] = 1;
    board[-10][10] = 2;
    board[10][-10] = 3;
    board[10][10] = 4;
    board[0][0] = 5;
    for (int i = -10; i <= 10; ++i)
    {
        for (int j = -10; j <= 10; ++j)
        {
            cout << " " << board[i][j];
        }
        cout << endl;
    }
    return 0;
}

This creates a normal 21x21 array but then it also creates a pointer to a fake array which is initialised to point at the centre of the real array. 这将创建一个普通的21x21数组,但随后还会创建一个指向假数组的指针,该指针被初始化为指向实际数组的中心。 You can then use this fake pointer as if it were a real array with indices ranging from -10 to +10 (inclusive). 然后,您可以使用这个伪指针,就好像它是一个实际数组,索引范围为-10到+10(含)。

LIVE DEMO 现场演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM