2

How does subscripting multiple times work for std::array even though all operator[]returns is a reference, without using any proxy-objects (as shown here)?

Example:

#include <iostream>
#include <array>

using namespace std;

int main()
{

    array<array<int, 3>, 4> structure;
    structure[2][2] = 2;
    cout << structure[2][2] << endl;

    return 0;
}

How/why does this work?

3
  • When performing operations on references, you perform them on objects they refer to. Commented Sep 10, 2014 at 15:11
  • 4
    The example you link to shows how to use a proxy object so that you can subscript an object multiple times when you have a single object that models a multidimensional array. With array<array<T, N>, M> you literally have an array of arrays, so subscripting the outer object returns a reference to an array, which you can then subscript. No proxy needed, because this case is much simpler! Commented Sep 10, 2014 at 15:11
  • When you have a pointer int*p, you can compute p+6+2. Same thing. Commented Sep 10, 2014 at 15:14

2 Answers 2

7

You simply call structure.operator[](2).operator[](2), where the first operator[] returns a reference to the third array in structure to which the second operator[] is applied.

Note that a reference to an object can be used exactly like the object itself.

Sign up to request clarification or add additional context in comments.

Comments

6

As you say, structure[2] gives a reference to an element of the outer array. Being a reference, it can be treated exactly as if it were an object of the same type.

That element is itself an array (array<int,3>), to which a further [] can be applied. That gives a reference to an element of the inner array, of type int.

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.