Click to See Complete Forum and Search --> : how to use operator [][]


carnaz
April 24th, 2003, 03:44 AM
Hallo everyBUDDY ;)

maybe it's a repost, but I didn't find it here. I made vectors and matrices classes and to access single cell I used () operator. the problem was how to use a [] operator to index 2 dimensional array like matrix[1][5]. I made it like matrix(1,5) which is neither elegant nor widely used. It could confuse in the future. Does anybody have an idea how to trick one argument and twice used operator [] ?

thans a lot :rolleyes:
sincerelly carnaz

Gabriel Fleseriu
April 24th, 2003, 03:48 AM
You need a proxy class. Have a look at this code:

#include <vector>
#include <iostream>


template <typename T>
class array
{
public:
array(int rows, int cols):
data_(rows*cols),
rows_(rows),
cols_(cols),
proxy_(&data_, cols_, 0){}
array(const array &rhs):
data_(rhs.data_),
rows_(rhs.rows_),
cols_(rhs.cols_),
proxy_(&data_, cols_, 0){};
private:
class array_proxy
{
public:
array_proxy(std::vector<T> *ptr, int cols, int row):
data_(ptr),
cols_(cols),
row_(row){};
void set_row(int i){row_=i;}
T& operator[] (int i){return (*data_)[cols_*row_+i];}
const T& operator[](int i)const {return (*data_)[cols_*row_+i];}
private:
std::vector<T> *data_;
int cols_;
int row_;
};
public:
array_proxy& operator [](int i){proxy_.set_row(i); return proxy_;}
const array_proxy& operator [](int i) const {proxy_.set_row(i); return proxy_;}
array & operator = (const array & rhs){array tmp(rhs); swap(tmp); return *this;}
private:
void swap(array & rhs)
{
data_.swap(rhs.data_);
rows_=rhs.rows_;
cols_=rhs.cols_;
proxy_.data_=rhs.proxy_.data_;
}
private:
std::vector<T> data_;
int rows_, cols_;
array_proxy proxy_;
};



int main()
{
int i, j;
array<int> a(3, 4);
array<int>b = a;
for(i=0; i<3; ++i){
for(j=0; j<4; ++j){
a[i][j] = i+j;
}
}
for(i=0; i<3; ++i){
for(j=0; j<4; ++j){
std::cout<<a[i][j]<<" ";
}
std::cout<<std::endl;
}
std::cout<<std::endl;
for(i=0; i<3; ++i){
for(j=0; j<4; ++j){
std::cout<<b[i][j]<<" ";
}
std::cout<<std::endl;
}
char c;
std::cin.getline(&c, 1);
return 0;
}

PaulWendt
April 24th, 2003, 06:16 AM
Check out the following article; it may be of use to you:
http://www.cuj.com/articles/2000/0012/0012c/0012c.htm?topic=articles.

--Paul

carnaz
April 25th, 2003, 05:25 AM
thanks guys a lot, even if a little bit in advance. I didn't finished it yet, som maybe I'll ask again. :D

carnaz