Array Insert

From SwiftAPI

Jump to: navigation, search

Contents

C++

#include <vector>
using namespace std;
 
int a0[] = {1, 3, 7};
vector<int> a(a0, a0+3);
a.insert(a.begin()+2, 5);
// a == [1, 3, 5, 7]

C#

List<int> a = new List<int>() { 1, 3, 7 };
a.Insert(2, 5);
// a == { 1, 3, 5, 7 }

Java

import java.util.*;
 
List<Integer> a = new ArrayList<Integer>(Arrays.asList(1, 3, 7));
a.add(2, 5);
// a == [1, 3, 5, 7]

For arrays this doesn't make sense since arrays are fixed sized.

JavaScript

var a = [1, 3, 7];
a.splice(2, 0, 5);
// a == [1, 3, 5, 7]

Objective-C

developer.apple.com

- (void)insertObject:(id)anObject atIndex:(NSUInteger)index
NSMutableArray *a = [NSMutableArray arrayWithObjects:@1, @3, @7, nil];
[a insertObject:@5 atIndex:2];
// a == [1, 3, 5, 7]

Perl

@a = (1, 3, 7);
splice(@a, 2, 0, 5);
# @a == (1, 3, 5, 7)

PHP

$a = array(1, 3, 7);
array_splice($a, 2, 0, 5);
// $a == array(1, 3, 5, 7)

Python

a = [1, 3, 7]
a.insert(2, 5)
# a == [1, 3, 5, 7]

Ruby

a = [1, 3, 7]
a.insert(2, 5)
# a == [1, 3, 5, 7]

Swift

var a = [1, 3, 7]
a.insert(5, atIndex: 2)
// a == [1, 3, 5, 7]
Personal tools