1

I have a pretty simple array class, based on the vector class:

class myarray{
private:
    vector<double> data_;
    int size_; 
public:
/// Constructor that allocates the memory
myarray(const int& nx): size_(nx) {
  data_.resize(size_);
}
blah, blah, blah...

I want the user to be able to assign each element of myarray individually. For example, after declaring the object

myarray A(10);

I want the user to be able to do the following:

A(0) = 1; 
A(1) = 2; 

and etc. How do I do this?

Bluegreen17
  • 983
  • 1
  • 11
  • 25
  • I'd suggest `A[0]` etc, but [operator overloading](http://stackoverflow.com/questions/4421706/operator-overloading). – chris Mar 29 '14 at 06:38
  • What will be the additional functionality that your "array" will provide? Why will it be better than using `std::vector` directly? – LihO Mar 29 '14 at 06:39
  • If the new `myarray` has all of the same functionality as the `std::vector` and/or `std::array`, then this must be an exercise for homework. Is this correct? – CPlusPlus OOA and D Mar 29 '14 at 06:41
  • No. I am adding functionality to an existing array class that my coworkers are using. Eventually I want to interface this with python. Moreover, I have to use this because this class is being used by a whole sweet of other classes. So unfortunately, it's too late to use the standard vector class. – Bluegreen17 Mar 29 '14 at 06:45

2 Answers2

2

Provide a couple of overloads for operator()(size_t):

int& operator()(std::size_t i) { return data_[i]; }

const int& operator()(std::size_t i) const { return data_[i]; }

The first version allows you to read and write elements of a mutable instance of myarray. The second allows you to read elements of a const instance of myarray (or access via const reference or pointer-to-const.)

Note: strictly speaking, the correct type of the index would be std::vector<double>::size_type. This is usually the same as std::size_t, but may be different if a custom allocator is used.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
1

Provide an overloaded operator()(int i) function.

int operator()(int i ) { return data_[i]; }

Whether it is the right thing to do or not, it's your call.

If you want to be able to use:

A(0) = 5;

change the function to return a reference. In fact, have an overload of the const variety too.

int& operator()(int i ) { return data_[i]; }
int const& operator()(int i ) const { return data_[i]; }
R Sahu
  • 204,454
  • 14
  • 159
  • 270