Polyglot CheatSheet - List / Vector / Array

Updated: 2021-11-19

Abstractions

C++

  • std::vector: similar to C arrays, but dynamically-resizable;
  • std::list/std::forward_list: a linked list of values; and
  • std::deque: similar to a vector in that it allows random access, but also supports constant time insertion and removal from both ends of the array.

Rust

  • std::vec::Vec or std::collections::VecDeque
  • std::collections::LinkedList

Create: Empty

Java

List<Integer> v = new ArrayList<>();

Rust

let mut l = LinkedList::new();

Hack

Hack Array:

$v = vec[]

Hack Collection:

$v = Vector{}

PHP

array()

Python

>>> [[0] * 4] * 4
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

Create: Literal

C++

#include <vector>

std::vector<int> v {1, 2, 3, 4};

// or

std::vector<int> v = {1, 2, 3, 4};

Rust

let v = vec![5, 4, 3, 2, 1];

Java

// Array
String[] optypes = new String[]{"A", "B", "C"};

// List
List<Integer> v =
    new ArrayList<>(Arrays.asList(5, 4, 3, 2, 1));

Hack

$v = vec[1, 2, 3];

Ruby

>> numbers = ['zero', 'one', 'two']
=> ["zero", "one", "two"]

Create: From Existing (Clone)

Java

List<Integer> copy = new ArrayList<>(origin)

Javascript

const clone = originArray.slice(0);

Hack

$v = vec($container);

Get By Index

Ruby

>> numbers[1]
=> "one"

Add Elements

C++

Use push_back or emplace_back:

std::vector<int> v = {1, 2};
v.emplace_back(3);
v.push_back(4);

emplace_back will forward the args to the constructor, while push_back takes the value as the input:

std::vector<std::pair<std::string, int>> v = {std::make_pair("a", 1),
                                              std::make_pair("b", 2)};
v.emplace_back("c", 3);
v.push_back(std::make_pair("d", 4));

Java

list.push()

Python

list.append()

Javascript

// insert, front
list.unshift();

// insert, back
list.push();

Hack

$v[] = 4;

Ruby

>> numbers.push('three', 'four')
=> ["zero", "one", "two", "three", "four"]

Remove Element

Javascript

// delete from back
list.pop();

// delete from front
list.shift();

Delete without changing indices of other elements(leaving a hole)

delete array[i];

Delete and shift other elements forward(modifying array in place:

var index = array.indexOf(5);
if (index > -1) {
  array.splice(index, 1);
}

Delete by filtering

keys.filter((key) => key != 'foo');

Ruby

>> numbers.drop(2)
=> ["two", "three", "four"]

Last Item

C++

  • vector::back: returns a reference
  • vector::end: returns an iterator just past the element

Contains

C++

Use std::find

std::vector<int> v { 10, 20, 30, 40 };
int val = 20;
if (std::find(v.begin(), v.end(), val) != v.end()) {
  ...
}

Hack

Hack Array:

C\contains_key($v, 1)

or

C\contains($v, 3)

Python

Use in:

>>> a = [1, 2, 3]
>>> 1 in a
True
>>> 4 in a
False

Javascript

Use includes:

arr.includes(element);

Count Elements

Hack

C\count($v)

Type Signature

Hack

vec<TValue>

Type Test

Hack

is_vec($v)

Join As String

Python

join is a method of string instead of a list, since any iterable can be joined.

>>> "|".join(["a", "b", "c"])
'a|b|c'

Scala

Use mkString

scala> List("a","b","c").mkString("|")
res1: String = a|b|c

Java 8+

String joined = String.join(",", Arrays.asList("a", "b", "c"));

or

String joined = Arrays.asList("a", "b", "c").stream().collect(Collectors.joining(","));

Manipulate before joining, e.g. to Uppercase

String joined = Arrays.asList("a", "b", "c")
    .stream()
    .map(String::toUpperCase)
    .collect(Collectors.joining(","));

PHP

implode

Join Two Arrays

javascript

[1].concat([2])[(1, 2)];

IndexOf

var array = [2, 5, 9];
var index = array.indexOf(5);

Subarray

Scala

arr.drop(2)

Python

arr[2:]

Javascript

arr.slice();

Convert To Other Collections

Deconstruct

Javascript

const [a, b, c] = str.split('-');

PHP

list($a, $b, $c) = Str\split(",", $str);

Max/Min

Java

Java 8+

int[] a = new int[]{1,2,3};
int min = Arrays.stream(a).min().getAsInt();

Javascript

Math.max and Math.min do not work on arrays, for example Math.max(1,2,3,4). To get the max/min of an array, use apply

Math.max.apply(Math, [1, 2, 3, 4]);
Math.min.apply(Math, [1, 2, 3, 4]);

Flatten

Python

There's no flatten builtin, but can use list comprehension:

flat_list = [item for sublist in nestedlist for item in sublist]

which means:

for sublist in nestedlist:
    for item in sublist:
        flat_list.append(item)

zip

Python

>>> keys = ['a', 'b', 'c']
>>> values = ['1', '2', '3']
>>> list(zip(keys, values))
[('a', '1'), ('b', '2'), ('c', '3')]

Javascript

const a = [1, 2, 3]
const b = ['A', 'B', 'C']
a.map((v, i) => [v, b[i]]
// [[1, 'A'], [2, 'B'], [3, 'C']]