Reputation: 1279
I am creating a class called intArray. It should behave identical to the std::array but only with integers. I got a bit stuck in the constructor where I need to fill the array with zeros, given the size. I am NOT using the std::array, I am just trying to sort of re-create it.
I was thinking along the lines of having n integers (where n is the fixed array size) that are consecutive in memory and a pointer, head, that points to the first integer... Then the rest of the integers could be easily accessed by getting the i'th memory location after the memory location of the data the head is pointing to.
Basically, how should I initialize/fill an array with zeroes inside its constructor?
Is this a valid way to implement the constructor? If so, is there a better way? If not, how should I accomplish this task?
Sorry, it's a confusing question, just comment if you need any clarity.
(not sure how to create 'n' independent integers)
intArray::intArray(size_t n){
intArray::size = n;
int num = 0;
intArray::head = num //head is an int*
//have no idea how to do this...
for(int i=0; i<n; i++){
&num + 1 = 0; //trying to set next value in memory to 0
//obviously not gonna work!
}//end loop
}//end of constructor
I greatly appreciate any answers/comments. Let me now if I missed anything, thanks!
Upvotes: 0
Views: 189
Reputation: 63471
Firstly, what you are really doing is recreating vector
, not array
, because your construction parameter is not required to be known at compile time. With that in mind, you need to be using dynamic memory unless you change your approach to passing the size as a template parameter and storing an actual array instead of pointer (this is exactly how std::array
works).
And so, using dynamic memory, the constructor becomes:
intArray::intArray( size_t n )
: head( new int[ n ] )
, currentSize( n )
{
std::fill( head, head + n, 0 );
}
If you don't want to use std::fill
, then the equivalent loop is:
for( size_t i = 0; i < n; i++ )
{
head[i] = 0;
}
Upvotes: 2