vector class imitation
Jan 28, 2011 at 8:18am UTC
I am trying to imitate the vector class with arrays
the constructor is
1 2 3 4 5 6 7 8 9 10 11
IntVector:: IntVector(unsigned size, int value)
{
vsize=size;
vcapacity=size;
data=new int [value];
for (unsigned int i=0; i<size; i++)
{
data[i]=value;
}
}
the function im having trouble with is
1 2 3 4 5 6 7
const int &IntVector:: at(unsigned int index) const
{
int temp=data[index];
int &ref=temp;
return ref;
}
in the main.cpp i try to use cout<<f.at(2); and it gives me an error
can anyone help?
Jan 28, 2011 at 8:50am UTC
You can do it like this:
1 2 3 4
const int &IntVector:: at(unsigned int index) const
{
return data[index];
}
better don't return the reference but a copy of the int and check the index
Jan 29, 2011 at 3:51pm UTC
Make sure that you are accessing a valid index. Add this in your
at( );
function:
1 2 3 4 5
if ( ( index >= 0 ) && ( index <= YourMaxArrayLength - 1 ) )
{
// The given index is not lower that zero( first ) and it's not greater that the last
return data[ index ];
}
Topic archived. No new replies allowed.