samedi 30 janvier 2016

Efficient way to initialize array with a byte sequence?

Let's say I have a byte sequence of some odd size n, with n = 3 for the sake of this example:

char source[n] = "abc"

And I have a memory range of sufficient size to hold m copies of this sequence:

char * dest = new char[m*n]

Now I want to initialize dest with those m copies of source. Sure, I could use a nested loop:

for ( unsigned i1 = 0; i1 < m; ++i1 )
{
    for ( unsigned i2 = 0; i2 < n; ++i2 )
    {
        dest[ i1 * n + i2 ] = source[ i1 ];
    }
}

But somehow this lacks all the finesse that usually tells me that I got the "right" solution for a problem.

Does C++ offer some more efficient way for this?

Aucun commentaire:

Enregistrer un commentaire