Let's say I have a byte sequence of some size n (which could be 1..4 elements in the "real" code), with n = 3 for the sake of this example:
char source[n] = { 'a', 'b', 'c' }
And I have a memory range of sufficient size to hold m copies of this sequence:
char * dest = new char[m*n]
(And yes, I know std::vector, and yes, it's generally to be preferred over new'ing your own memory, and no, it's not an option for the code I am currently working on -- and anyway the problem would still be the same.)
Now I want to initialize dest with those m copies of source. There are various ways to do m copies of a single value, but apparently none for doing m copies of a sequence of values. 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?
std::vector?std::vectoris not an option in the larger scheme this problem is a part of.memcpyto avoid nested loop.nwould be 4 forchar source[n] = "abc".