Out of bounds

For this question in an assignment I have

float vec::operator[](const int i) const
{
return mem[i];
}

Write a version of this access operator which returns the first, or last, entry (as appropriate) when an
out of bounds occurs.

I was thinking of using catch (const std::out_of_range& oor) but I am not sure how to return the first or last entry as appropriate.
How about checking the size of the container?
1
2
3
4
5
6
7
float vec::operator[](const int i) const
{
  if (i < 0) return mem[0];
  if (i  is too big ) return mem[last_element];

  return mem[i];
}
I don't know what type mem is, but my guess is that it does no bounds checking, so no exception is going to be thrown.

You need to do the bounds checking yourself, that's the point of the exercise.
e.g. if (i < 0) --> return mem[0]
if (i > {number of elements in mem} - 1) --> return mem[{number of elements in mem -1}].

What is not specified is what happens when mem is empty. In that case, even mem[0] will be out of bounds. You might want to throw an exception.
Last edited on
float vec::operator[](const unsigned int i) const //unsigned, unless you are intentionally using a pointer to allow negative indexing.
{
return mem[min(i,outtabounds)]; //etc
}

you gotta do what they tell you but returning the wrong thing (some other item that was not asked for) and acting as if nothing happened feels like trouble to me.
if you know the bounds, and you should, there isn't any reason to try/catch here (you can, but its overkill) … just fix it. by getting rid of the signed, it has to be either legal or too large... so min cleans it out when outtabounds is the biggest legal index.
Last edited on
Topic archived. No new replies allowed.