Question

I have an array whose size and values keep changing during execution all the time. I want to do that with minimum possible performance overhead.

Instead ochanging array size I simply have member int variables indicating start and end Index and I expect consumer of this array to use these indices in the foor loop. The risk is, if the consumer does not use the start and endindex it may end up causing error. Is there a better way of doing that?

So what I have is:

MyClass
{

public:
BusinessClass                   myArray[MAX_COUNT];//the array

int StartIndex; //start index
int EndIndex;   //End index

Logic()
{
//modified the array and changes start and end index
}

}

MyConsumer
{

MyClass obj;

public:
void ReadArray()
{
for (int i = obj.StartIndex ; i <obj.EndIndex; i++)
{
//perform logic
}
}

}
Was it helpful?

Solution

Instead of exposing the underlying array, you could have a length method that returns EndIndex-StartIndex, and an array operator that returns an item from the array offset by the value of the StartIndex.

The you would access the items in the array like this:

for (int i = 0; i < obj.length(); i++) {
  BusinessClass &item = obj[i];
}

The MyClass class would look something like this:

class MyClass {
public:
  size_t length() const {
    return EndIndex - StartIndex;
  };
  BusinessClass &operator[](size_t off) {
    return myArray[StartIndex+off];
  };

private:
  BusinessClass myArray[MAX_COUNT];

  int StartIndex; //start index
  int EndIndex;   //End index
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top