简体   繁体   中英

Fill a custom integer array with ints

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.


Here's my constructor so far:

(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!

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM