473,408 Members | 1,854 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,408 software developers and data experts.

operator [] or what ?

I write 2-dimensional array's wrapper class.
And how I can access to the one element through the operator [] ?
I need something like this:
CMyArray<int> A(4, 4); // array "int A[4][4]";
int value = A[2][3];

//------------------------
template <class TType>
class CMyArray
{
public:
CMyArray(int x, int y);
.....
private:
TType **data;
....
};

Creation of array:
data = new TType*[x];
for (int i=0; i<x; i++) data[i] = new TType[y];

And I need for this class operator [] - how I can write it ?

P.S. I know about STL, vector etc. but I want to try to do it manually by
myself.
(sory for my english)
Dec 11 '05 #1
18 1479

Marchello wrote:
I write 2-dimensional array's wrapper class.
And how I can access to the one element through the operator [] ?
I need something like this:
CMyArray<int> A(4, 4); // array "int A[4][4]";
int value = A[2][3];

//------------------------
template <class TType>
class CMyArray
{
public:
CMyArray(int x, int y);
....
private:
TType **data;
...
};

Creation of array:
data = new TType*[x];
for (int i=0; i<x; i++) data[i] = new TType[y];

And I need for this class operator [] - how I can write it ?


1. You can write operator[] to return TType*

TType* CMyArrayoperator[](int x)
{
return data[x];
}

2. Alternatively, you can also use operator(). I have modified the code
a bit to use template parameters x and y instead of giving x and y in
constructors. Of course this needs the values of x and y to be known at
compile time.

template <class TType, int x, int y>
class CMyArray
{
public:
CMyArray()
{
data[1][2] = 100;
}

TType operator()(int m, int n)
{
return data[m][n];
}

private:
TType data[x][y];
};

Usage :
CMyArray<int, 4,5> arr;
int p = arr(4,5) // same as arr[4][5]

HTH.

Dec 11 '05 #2

Marchello wrote:
I write 2-dimensional array's wrapper class.
And how I can access to the one element through the operator [] ?
I need something like this:
CMyArray<int> A(4, 4); // array "int A[4][4]";
int value = A[2][3];

//------------------------
template <class TType>
class CMyArray
{
public:
CMyArray(int x, int y);
....
private:
TType **data;
...
};

Creation of array:
data = new TType*[x];
for (int i=0; i<x; i++) data[i] = new TType[y];

And I need for this class operator [] - how I can write it ?

P.S. I know about STL, vector etc. but I want to try to do it manually by
myself.
(sory for my english)

just write like this:
TType operator[](int a)
{
return data[a];
}
is ok

Dec 11 '05 #3

Neelesh Bodas wrote:
Marchello wrote:
I write 2-dimensional array's wrapper class.
And how I can access to the one element through the operator [] ?
I need something like this:
CMyArray<int> A(4, 4); // array "int A[4][4]";
int value = A[2][3];

//------------------------
template <class TType>
class CMyArray
{
public:
CMyArray(int x, int y);
....
private:
TType **data;
...
};

Creation of array:
data = new TType*[x];
for (int i=0; i<x; i++) data[i] = new TType[y];

And I need for this class operator [] - how I can write it ?


1. You can write operator[] to return TType*

TType* CMyArrayoperator[](int x)
{
return data[x];
}

2. Alternatively, you can also use operator(). I have modified the code
a bit to use template parameters x and y instead of giving x and y in
constructors. Of course this needs the values of x and y to be known at
compile time.

template <class TType, int x, int y>
class CMyArray
{
public:
CMyArray()
{
data[1][2] = 100;
}

TType operator()(int m, int n)
{
return data[m][n];
}

private:
TType data[x][y];
};

Usage :
CMyArray<int, 4,5> arr;
int p = arr(4,5) // same as arr[4][5]

HTH.


no need write like this,arr[4][5] can be call twice operator[] instead.

Dec 11 '05 #4
* Marchello:
I write 2-dimensional array's wrapper class.

And I need for this class operator [] - how I can write it ?


Can be done but either gives unsafe access to internal representation,
or inefficient.

Instead, use a member function 'at'.

Or operator() if you really like operators.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Dec 11 '05 #5

"Marchello" <ma*******@rtf-15.ntu-kpi.kiev.ua> wrote in message
news:dn**********@news.ntu-kpi.kiev.ua...
[SNIP]
Creation of array:
data = new TType*[x];
for (int i=0; i<x; i++) data[i] = new TType[y];

And I need for this class operator [] - how I can write it ?

P.S. I know about STL, vector etc. but I want to try to do it manually by
myself.
(sory for my english)


In addition to what Neelesh and Alf already have said you might want to
check out the FAQ on this topic, where you'll find extensive information
about the pros and cons of () vs. [][]

http://www.parashift.com/c++-faq-lit...html#faq-13.10

Cheers
Chris
Dec 11 '05 #6
Thanks to All !
In addition to what Neelesh and Alf already have said you might want to
check out the FAQ on this topic, where you'll find extensive information
about the pros and cons of () vs. [][]
http://www.parashift.com/c++-faq-lit...html#faq-13.10


Yes indeed. It's good info.
Dec 11 '05 #7

<us******@gmail.com> wrote in message
news:11*********************@g43g2000cwa.googlegro ups.com...
[SNIP] just write like this:
TType operator[](int a)
{
return data[a];
}
is ok


This is not okay because the subscript operator requires an array or pointer
type and TType is neither.

Chris
Dec 11 '05 #8
Alf P. Steinbach wrote:
* Marchello:
I write 2-dimensional array's wrapper class.

And I need for this class operator [] - how I can write it ?

Can be done but either gives unsafe access to internal representation,
or inefficient.


Where did you get the "inefficient" notion ? I suspect you're thinking
the use of a proxy class, however in all cases I have seen, using a
proxy class will be optimized to exactly the same code even with minimal
levels of optimization on at least 2 different compilers I looked at.

Instead, use a member function 'at'.

Or operator() if you really like operators.


The only real difference between using [] vs () is compatability with
legacy code and ability to use the generic programming paradigm across
classes and regular C++ arrays, which, IMHO is a big deal.
Dec 11 '05 #9
Chris Theis wrote:
"Marchello" <ma*******@rtf-15.ntu-kpi.kiev.ua> wrote in message
news:dn**********@news.ntu-kpi.kiev.ua...
[SNIP]
Creation of array:
data = new TType*[x];
for (int i=0; i<x; i++) data[i] = new TType[y];

And I need for this class operator [] - how I can write it ?

P.S. I know about STL, vector etc. but I want to try to do it manually by
myself.
(sory for my english)

In addition to what Neelesh and Alf already have said you might want to
check out the FAQ on this topic, where you'll find extensive information
about the pros and cons of () vs. [][]

http://www.parashift.com/c++-faq-lit...html#faq-13.10


While the faq is in general a good thing, this one is particularly
misleading.

The real scoop is that there is no difference between () and [][] when
implemented correctly except for compatability with legacy code and
generic programming in which the [][] style is better.
Dec 11 '05 #10
Chris Theis wrote:
<us******@gmail.com> wrote in message
news:11*********************@g43g2000cwa.googlegro ups.com...

[SNIP]
just write like this:
TType operator[](int a)
{
return data[a];
}
is ok

This is not okay because the subscript operator requires an array or pointer
type and TType is neither.


I'm sure Mr/s root meant:

TType * operator[](int a)
{
return data[a];
}
Dec 11 '05 #11
sorry for my mistake.~_~

Dec 11 '05 #12

Gianni Mariani wrote:
Chris Theis wrote:

http://www.parashift.com/c++-faq-lit...html#faq-13.10


While the faq is in general a good thing, this one is particularly
misleading.

The real scoop is that there is no difference between () and [][] when
implemented correctly except for compatability with legacy code and
generic programming in which the [][] style is better.


Neither one is better or worst wrt compatability with "legacy" code.
You will _never_ be able to create an object class that can be passed
off as a C array to a function expecting such so that is just a
pointless argument. You can write template code that depends on C
arrays, but that isn't legacy code. If you happen to be dealing with
code written in C++ that depends on the array syntax you can always
create a wrapper or proxy, which is the only correct way to implement
[][] anyway...then you can slowly replace that code, which is the goal
when dealing with "legacy" code. If you need to pass a C array to an
algorithm that uses () syntax or a function you can always implement a
VERY simple adapter to provide that syntax and in fact if you've done
just a little thinking ahead you already have one.

() is never worst than [][]. You still have yet to show any situation
where it is. The only implementation you have ever provided of [][]
is destined for failure in large projects. What is worst is that it is
likely to fail in ways very difficult to debug.

Dec 11 '05 #13

Marchello wrote:
And I need for this class operator [] - how I can write it ?


Are you sure you need it?

Correctly implementing [][] for an object is not a simple matter at
all. Returning a pointer to your internall data buffer is NOT a good
design.

Mtx mtx(4,4);

mtx[2][6] = 5; // perfectly valid.
mtx[3][6] = 5; // perfectly valid - buffer overrun - undefined
behavior!!

There is no way for your class to protect itself from its users if it
offers up a pointer to its internal data member. The ONLY way to stop
these things from happening is to make sure ALL developers only use
these operators a certain way. Someday someone will decide they want
to do it another way. Frankly, if you do this there is no reason to
have the class at all. Better just to implent as a struct or simply a
basic array. The only thing your class offers by behaving like that is
the extra overhead of being a class! (which granted is not much but the
point is that it's pointless)

Many of the arguments against doing this are the same for arguments
against using dynamic arrays in c++ instead of opting for classes like
vector or string. Using classes like vector and string greately reduce
the time spent chasing down problems like buffer overruns, invalid
pointers, and memory alloc/dealloc issues.

If you absolutely MUST use [][] then have a look at the proxy class
introduced in the thread entitled "Two dimensional dynamic arrays".
This class does much of what is needed to implement [][] in a class
without doing bad and dangerous things.

Dec 11 '05 #14
* Gianni Mariani:
Alf P. Steinbach wrote:
* Marchello:
I write 2-dimensional array's wrapper class.

And I need for this class operator [] - how I can write it ?

Can be done but either gives unsafe access to internal representation,
or inefficient.


Where did you get the "inefficient" notion ? I suspect you're thinking
the use of a proxy class, however in all cases I have seen, using a
proxy class will be optimized to exactly the same code even with minimal
levels of optimization on at least 2 different compilers I looked at.


It's quite possible that I'm wrong.

Meaning: I was repeating the Common Wisdom, as set forth in the Holy
FAQ, without thinking or testing.

However, while I now think my seemingly simple argument possibly may not
stand up to scrutiny, or it may, I don't know! ;-), I still think
operator() or at() is in general the way to go, because it's generally
simpler than doing proxies and allows more flexibility (e.g., easily
changing row/col order, adding bounds checking, passing a single
argument that represents an (x,y) index, customizing such things via
template policies, and so on).

Instead, use a member function 'at'.

Or operator() if you really like operators.


The only real difference between using [] vs () is compatability with
legacy code and ability to use the generic programming paradigm across
classes and regular C++ arrays, which, IMHO is a big deal.


This seems to be a question of which access method is most used, and so
which assumption will require the least use of adapters. Libraries like
Blitz and Boost ublas use operator(). My impression is that operator()
is by far most common, and so assuming operator() in new code will
require the least use of adapters.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Dec 11 '05 #15

Alf P. Steinbach wrote:
* Gianni Mariani:
Alf P. Steinbach wrote:
* Marchello:

>I write 2-dimensional array's wrapper class.
>
>And I need for this class operator [] - how I can write it ?
Can be done but either gives unsafe access to internal representation,
or inefficient.


Where did you get the "inefficient" notion ? I suspect you're thinking
the use of a proxy class, however in all cases I have seen, using a
proxy class will be optimized to exactly the same code even with minimal
levels of optimization on at least 2 different compilers I looked at.


It's quite possible that I'm wrong.

Meaning: I was repeating the Common Wisdom, as set forth in the Holy
FAQ, without thinking or testing.


This is not common wisdom. This is a common mistake that is
perpetuated by being posted in a well known C++ FAQ.
Most of the information on this FAQ is good, but this happens to be one
item that is completely wrong.

I highly recommend against following this particular item on the FAQ.

I recommend using [][] syntax over using operator() syntax.

If you need the extra flexibility that you think you can get using
operator(), then use a get function. (get_array(int x, int y)).
A get function is less ambiguous and gives you all the functionality
that you can get using operator().
If you don't need this extra flixibility, and just want something
simple, then use the following code, which allows for using [][] syntax
safely and efficiently, and less ambiguous then using operator().

http://code.axter.com/dynamic_2d_array.h

Dec 11 '05 #16

Marchello wrote:
I write 2-dimensional array's wrapper class.
And how I can access to the one element through the operator [] ?
I need something like this:
CMyArray<int> A(4, 4); // array "int A[4][4]";
int value = A[2][3];

//------------------------
template <class TType>
class CMyArray
{
public:
CMyArray(int x, int y);
....
private:
TType **data;
...
};

Creation of array:
data = new TType*[x];
for (int i=0; i<x; i++) data[i] = new TType[y];

And I need for this class operator [] - how I can write it ?

P.S. I know about STL, vector etc. but I want to try to do it manually by
myself.

Check out the following link:
http://code.axter.com/dynamic_2d_array.h

Dec 11 '05 #17

Axter wrote:
Check out the following link:
http://code.axter.com/dynamic_2d_array.h


Still haven't fixed that thing??!!

Dec 12 '05 #18

<ro**********@gmail.com> wrote in message
news:11*********************@f14g2000cwb.googlegro ups.com...

Gianni Mariani wrote:
Chris Theis wrote:

> http://www.parashift.com/c++-faq-lit...html#faq-13.10


While the faq is in general a good thing, this one is particularly
misleading.

The real scoop is that there is no difference between () and [][] when
implemented correctly except for compatability with legacy code and
generic programming in which the [][] style is better.


Neither one is better or worst wrt compatability with "legacy" code.
You will _never_ be able to create an object class that can be passed
off as a C array to a function expecting such so that is just a
pointless argument.

[SNIP]

Why? Probably I don't understand you correctly but what about the standard
container vector, which you can pass nicely to functions expecting C arrays.

Cheers
Chris
Dec 12 '05 #19

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: Paul Davis | last post by:
I'd like to overload 'comma' to define a concatenation operator for integer-like classes. I've got some first ideas, but I'd appreciate a sanity check. The concatenation operator needs to so...
1
by: joesoap | last post by:
Hi can anybody please tell me what is wrong with my ostream operator??? this is the output i get using the 3 attached files. this is the output after i run assignment2 -joesoap #include...
5
by: Jason | last post by:
Hello. I am trying to learn how operator overloading works so I wrote a simple class to help me practice. I understand the basic opertoar overload like + - / *, but when I try to overload more...
34
by: Pmb | last post by:
I've been working on creating a Complex class for my own learning purpose (learn through doing etc.). I'm once again puzzled about something. I can't figure out how to overload the assignment...
0
by: A. W. Dunstan | last post by:
I'm porting some code to Visual C++ and have run into a problem - the compiler won't use a user-written cast operator. The code uses an envelope-letter approach to passing (potentially) large...
5
by: raylopez99 | last post by:
I need an example of a managed overloaded assignment operator for a reference class, so I can equate two classes A1 and A2, say called ARefClass, in this manner: A1=A2;. For some strange reason...
3
by: y-man | last post by:
Hi, I am trying to get an overloaded operator to work inside the class it works on. The situation is something like this: main.cc: #include "object.hh" #include "somefile.hh" object obj,...
18
by: Ranganath | last post by:
Why is throw keyword considered as an operator?
17
by: Corey Cooper | last post by:
I have a class for which I needed to create an operator= function. I then use that as a base class for another class, which also needs an operator=. What is the syntax to use in the derived class...
19
by: C++Liliput | last post by:
I have a custom String class that contains an embedded char* member. The copy constructor, assignment operator etc. are all correctly defined. I need to create a map of my string (say a class...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.