Reputation: 2578
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?
Upvotes: 2
Views: 100
Reputation: 50063
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.
Upvotes: 7
Reputation: 254471
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
.
Upvotes: 6