views:

41

answers:

2

What is the most efficient way to insert one Vector into another at specific position?

For example:

var aa:Vector.<int> = Vector.<int>([1, 2, 3]);
var bb:Vector.<int> = Vector.<int>([9, 8, 7]);

This doesn't seems to work:

bb.splice(1, 0, aa);

The result is [9, 0, 8, 7].

A: 

If you need to concat one after the other, as PatrickS mentionned bb.concat will do the job.

If you need to insert values in the middle you'll need something like

for each (var i : int in aa.reverse())
{
    bb.splice(1,0,i);
}

or, more elegantly, this, if you cannot change aa

var insertingIndex : int = 2;
for each ( var i : int in aa )
{
    bb.splice( insertingIndex, 0, i );
    insertingIndex++;
}
Axelle Ziegler
For this loop what is variable "i" for?
zdmytriv
None of 2 examples are working and none of two examples are efficient. I still hope to find more efficient way then loop and splice.
zdmytriv
Care to define "not working" and "efficient" ? :)
Axelle Ziegler
+1  A: 

For the moment there is no builtin function other than doing a loop over the Vector, here two methods (i have not timed them).

If bb can be a new Vector you can do for example:

var insertIndex:int = 1;
bb=bb.slice(0, insertIndex).concat(aa).concat(bb.slice(insertIndex));

If bb cannot be change you can do a splice but with preparing the elements to insert into a new Array:

var insertIndex:int = 1;

var parms:Array=[insertIndex, 0]; // prepare the arguments for the splice call
var j:int = 2; // length of the parms array

var len:int = aa.length;

for (var i:int = 0; i < len; i++, j++){
    parms[j] = aa[i];
}

// call the splice with the new arguments
bb.splice.apply(bb, parms);
Patrick
I think concat does a loop behind the hood, so the two solutions should be roughly equivalient performance wise.
Axelle Ziegler
Looks like slice.concat.concat is the most efficient so far.
zdmytriv