phpday 2027 - Call for Papers

The Vector class

(PECL ds >= 1.0.0)

Introduction

A Vector is a sequence of values in a contiguous buffer that grows and shrinks automatically. It’s the most efficient sequential structure because a value’s index is a direct mapping to its index in the buffer, and the growth factor isn't bound to a specific multiple or exponent.

Strengths

  • Supports array syntax (square brackets).
  • Uses less overall memory than an array for the same number of values.
  • Automatically frees allocated memory when its size drops low enough.
  • Capacity does not have to be a power of 2.
  • get(), set(), push(), pop() are all O(1).

Weaknesses

  • shift(), unshift(), insert() and remove() are all O(n).

Class synopsis

class Ds\Vector implements Ds\Sequence, ArrayAccess {
/* Constants */
const int MIN_CAPACITY = 8;
/* Methods */
public function allocate(int $capacity): void
public function apply(callable $callback): void
public function capacity(): int
public function clear(): void
public function contains(mixed ...$values): bool
public function copy(): Ds\Vector
public function filter(callable $callback = ?): Ds\Vector
public function find(mixed $value): mixed
public function first(): mixed
public function get(int $index): mixed
public function insert(int $index, mixed ...$values): void
public function isEmpty(): bool
public function join(string $glue = ?): string
public function last(): mixed
public function map(callable $callback): Ds\Vector
public function merge(mixed $values): Ds\Vector
public function pop(): mixed
public function push(mixed ...$values): void
public function reduce(callable $callback, mixed $initial = ?): mixed
public function remove(int $index): mixed
public function reverse(): void
public function reversed(): Ds\Vector
public function rotate(int $rotations): void
public function set(int $index, mixed $value): void
public function shift(): mixed
public function slice(int $index, int $length = ?): Ds\Vector
public function sort(callable $comparator = ?): void
public function sorted(callable $comparator = ?): Ds\Vector
public function sum(): int|float
public function toArray(): array
public function unshift(mixed $values = ?): void
}

Predefined Constants

Ds\Vector::MIN_CAPACITY

Changelog

Version Description
PECL ds 1.3.0 The class now implements ArrayAccess.
PECL ds 1.2.0 Ds\Vector::MIN_CAPACITY changed from 10 to 8.

Table of Contents

User Contributed Notes

There are no user contributed notes for this page.
Adding new notes is disabled. Please see the links in the Found A Problem? section.
To Top