Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Perl

Idiom #44 Insert element in list

Insert the element x at position i in the list s. Further elements must be shifted to the right.

Inserting the element x at a given position in the list s
splice(@s, $i, 0, $x);

The 0 tells splice we're replacing zero elements with $x at position $i, resulting in an insertion rather than replacement. The problem does not specify if the position i is 0 or 1 based - so be careful when implementing in real code.
s.insert (s.begin () + i, x);

New implementation...