operator[] and operator[][]
May 18, 2015 at 12:21pm UTC
Hello everyone!
Here's a simple code:
1 2 3 4 5
int &operator [](int in) const
{
cout << "pos:" << in << endl;
return in; // lets just return that pos.
}
This is how we define the operator [] for class.
Now how would we define the operator [][] ?
tried:
1 2 3 4 5
int &operator [][](int in1, int in2) const
{
cout << "pos:" << in1 << "/" << in2 << endl;
return in+in2;
}
but compiler didn't like that at all.
Is it possible to define such a thing?
What I'm planning to create is something like this:
http://www.cplusplus.com/reference/map/map/
I would call it 1 dimensional map.
Now i want to create something what i would call 2 or 3 dimensional map.
If there is a way to define operator [][], perhaps there is a way to define
[][][] too?
Thank you!
May 18, 2015 at 12:31pm UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
#include <cstddef>
template < typename T, std::size_t N > struct A
{
T& operator [] ( std::size_t pos ) { return array[pos] ; }
const T& operator [] ( std::size_t pos ) const { return array[pos] ; }
T array[N] ;
};
int main()
{
A< int , 10 > a1d ;
a1d[4] = 45 ;
A< A<int ,10>, 6 > a2d ;
a2d[4][3] = 99 ;
A< A< A<int ,10>, 7 >, 6 > a3d ;
a3d[4][3][2] = 8 ;
}
May 18, 2015 at 1:47pm UTC
a map inside of map im stupid, my apologies.
this would be my solution:
map<int ,map<int ,map<int ,int >>> my3dmap
thanks, i should have taken more time to think about it.
Topic archived. No new replies allowed.