1

I'm using: Windows 10, C++, Visual Studio 2013.

I'm looking for a way to access my 2D-array with negative numbers, for example I know this works with a 1D-array:

int myarray[35];

#define a (myarray + 50)

a[-45] = 0; //accesses myarray[5]

but can't figure out how to make it work with a 2D-array:

int foo[32][32]

#define bar (foo + 50)(foo + 50)

// The above does not work
5
  • This doesn't make a ton of sense. Even with your 1D-array if you access a[-5] you've done an out of bounds request. Commented Dec 16, 2016 at 12:04
  • Why would -45 give you item 5? That doesn't make any sense. Commented Dec 16, 2016 at 12:07
  • 1
    Because of the define in the line above.. it works.. Commented Dec 16, 2016 at 12:09
  • Okay, makes perfect sense! Here is the correct solution for setting index 5 to value 123 while using a negative index: (??--5)[array- -!! array] = 123;. Commented Dec 16, 2016 at 12:21
  • It does work, I just can't see why it's valuable. Perl for example allows negative indexes to access begining from the end of the array: perldoc.perl.org/perldata.html#Subscripts That is an incredibly helpful tool, but only because it's based on the size of the array. Commented Dec 16, 2016 at 12:26

1 Answer 1

1

You could use the same approach with 2D arrays as defines may have arguments:

int a[100][100];
#define b(x,y) a[x + 50][y + 50]

a[0][0] = 123;
cout << b(-50, -50) << endl; // prints 123

I personally would not like using this define-driven method as this limits the operations you could perform on your array (for example, you can't write b(1) to mean one specific row a[51] or have to define another macro for it).

To improve readability and maintainability, consider writing your own class, based on std::vector:

template<typename T>
class ShiftedVector {
private:
    int shift;
    std::vector<T> storage;
public:
    T& operator[] (int idx) {
        return storage[idx + shift];
    }
    // Definitions of other useful operations
}

ShiftedVector<ShiftedVector<int>> x; // Usage
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.