简体   繁体   中英

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). 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? 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.)

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)

One common (but rather sketchy) method is to do something like this (example for 21 x 21 board):

#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. You can then use this fake pointer as if it were a real array with indices ranging from -10 to +10 (inclusive).

LIVE DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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