Movatterモバイル変換


[0]ホーム

URL:


D Logo
Menu
Search

Library Reference

version 2.112.0

overview

Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page.Requires a signed-in GitHub account. This works well for small changes.If you'd like to make larger changes you may want to consider usinga local clone.

std.container

This module defines generic containers.

Construction

To implement the different containers, both struct and class basedapproaches have been used.std.container.util.make allows foruniform construction with either approach.
import std.container;// Construct a red-black tree and an array both containing the values 1, 2, 3.// RedBlackTree should typically be allocated using `new`RedBlackTree!int rbTree =new RedBlackTree!int(1, 2, 3);// But `new` should not be used with ArrayArray!int array = Array!int(1, 2, 3);// `make` hides the differencesRedBlackTree!int rbTree2 = make!(RedBlackTree!int)(1, 2, 3);Array!int array2 = make!(Array!int)(1, 2, 3);assert(rbTree == rbTree2);assert(array == array2);
Note thatmake can infer the element type from the given arguments.
import std.container;auto rbTree = make!RedBlackTree(1, 2, 3);// RedBlackTree!intauto array = make!Array("1","2","3");// Array!string

Reference Semantics

All containers have reference semantics, which means that afterassignment both variables refer to the same underlying data.
To make a copy of a container, use thec.dup container primitive.
import std.algorithm, std.container, std.range;Array!int originalArray = make!(Array!int)(1, 2, 3);Array!int secondArray = originalArray;assert(equal(originalArray[], secondArray[]));// changing one instance changes the other one as well!originalArray[0] = 12;assert(secondArray[0] == 12);// secondArray now refers to an independent copy of originalArraysecondArray = originalArray.dup;secondArray[0] = 1;// assert that originalArray has not been affectedassert(originalArray[0] == 12);
Attention: If the container is implemented as a class, using anuninitialized instance can cause a null pointer dereference.
import std.container;RedBlackTree!int rbTree;rbTree.insert(5);// null pointer dereference
Using an uninitialized struct-based container will work, because the structintializes itself upon use; however, up to this point the container will nothave an identity and assignment does not create two references to the samedata.
import std.container;// create an uninitialized arrayArray!int array1;// array2 does _not_ refer to array1Array!int array2 = array1;array2.insertBack(42);// thus array1 will not be affectedassert(array1.empty);// after initialization reference semantics work as expectedarray1 = array2;// now affects array2 as wellarray1.removeBack();assert(array2.empty);
It is therefore recommended to always construct containers usingstd.container.util.make.
This is in fact necessary to put containers into another container.For example, to construct anArray of ten emptyArrays, usethe following that callsmake ten times.
import std.container, std.range;auto arrOfArrs = make!Array(generate!(() => make!(Array!int)).take(10));

Submodules

This module consists of the following submodules:

The Primary Range of a Container

While some containers offer direct access to their elements e.g. viaopIndex,c.front orc.back, accessand modification of a container's contents is generally done throughits primaryrange type,which is aliased asC.Range. For example, the primary range type ofArray!int isArray!int.Range.
If the documentation of a member function of a container takesa parameter of typeRange, then it refers to the primary range type ofthis container. OftentimesTake!Range will be used, in which casethe range refers to a span of the elements in the container. Arguments tothese parametersmust be obtained from the same container instanceas the one being worked with. It is important to note that many generic rangealgorithms return the same range type as their input range.
import std.algorithm.comparison : equal;import std.algorithm.searching : find;import std.container;import std.range : take;auto array = make!Array(1, 2, 3);// `find` returns an Array!int.Range advanced to the element "2"array.linearRemove(array[].find(2));assert(array[].equal([1]));array = make!Array(1, 2, 3);// the range given to `linearRemove` is a Take!(Array!int.Range)// spanning just the element "2"array.linearRemove(array[].find(2).take(1));assert(array[].equal([1, 3]));
When anyrange can be passed as an argument toa member function, the documention usually refers to the parameter's templatedtype asStuff.
import std.algorithm.comparison : equal;import std.container;import std.range : iota;auto array = make!Array(1, 2);// the range type returned by `iota` is completely unrelated to Array,// which is fine for Array.insertBack:array.insertBack(iota(3, 10));assert(array[].equal([1, 2, 3, 4, 5, 6, 7, 8, 9]));

Container Primitives

Containers do not form a class hierarchy, instead they implement acommon set of primitives (see table below). These primitives each guaranteea specific worst case complexity and thus allow generic code to be writtenindependently of the container implementation.
For example the primitivesc.remove(r) andc.linearRemove(r) bothremove the sequence of elements in ranger from the containerc.The primitivec.remove(r) guaranteesΟ(nr log nc) complexity in the worst case andc.linearRemove(r) relaxes this guarantee toΟ(nc).
Since a sequence of elements can be removed from adoubly linked listin constant time,DList provides the primitivec.remove(r)as well asc.linearRemove(r). On the other handArray only offersc.linearRemove(r).
The following table describes the common set of primitives that containersimplement. A container need not implement all primitives, but if aprimitive is implemented, it must support the syntax described in thesyntax column with the semantics described in thedescription column, andit must not have a worst-case complexity worse than denoted in big-O notation intheΟ(·) column. Below,C means a container type,c isa value of container type,nx represents the effective length ofvaluex, which could be a single element (in which casenx is1), a container, or a range.
Container primitives
SyntaxΟ(·)Description
C(x)nxCreates a container of typeC from either another container or a range. The created container must not be a null reference even if x is empty.
c.dupncReturns a duplicate of the container.
c ~ xnc + nxReturns the concatenation ofc andr.x may be a single element or an input range.
x ~ cnc + nxReturns the concatenation ofx andc.x may be a single element or an input range type.
    Iteration
c.RangeThe primary range type associated with the container.
c[]log ncReturns a range iterating over the entire container, in a container-defined order.
c[a .. b]log ncFetches a portion of the container from keya to keyb.
    Capacity
c.empty1Returnstrue if the container has no elements,false otherwise.
c.lengthlog ncReturns the number of elements in the container.
c.length = nnc + nForces the number of elements in the container ton. If the container ends up growing, the added elements are initialized in a container-dependent manner (usually withT.init).
c.capacitylog ncReturns the maximum number of elements that can be stored in the container without triggering a reallocation.
c.reserve(x)ncForcescapacity to at leastx without reducing it.
    Access
c.frontlog ncReturns the first element of the container, in a container-defined order.
c.moveFrontlog ncDestructively reads and returns the first element of the container. The slot is not removed from the container; it is left initialized withT.init. This routine need not be defined if front returns aref.
c.front = vlog ncAssignsv to the first element of the container.
c.backlog ncReturns the last element of the container, in a container-defined order.
c.moveBacklog ncDestructively reads and returns the last element of the container. The slot is not removed from the container; it is left initialized withT.init. This routine need not be defined if front returns aref.
c.back = vlog ncAssignsv to the last element of the container.
c[x]log ncProvides indexed access into the container. The index type is container-defined. A container may define several index types (and consequently overloaded indexing).
c.moveAt(x)log ncDestructively reads and returns the value at positionx. The slot is not removed from the container; it is left initialized with T.init.
c[x] = vlog ncSets element at specified index into the container.
c[x]op= vlog ncPerforms read-modify-write operation at specified index into the container.
    Operations
e in clog ncReturns nonzero if e is found inc.
c.lowerBound(v)log ncReturns a range of all elements strictly less thanv.
c.upperBound(v)log ncReturns a range of all elements strictly greater thanv.
c.equalRange(v)log ncReturns a range of all elements inc that are equal tov.
    Modifiers
c ~= xnc + nxAppendsx toc.x may be a single element or an input range type.
c.clear()ncRemoves all elements inc.
c.insert(x)nx * log ncInsertsx inc at a position (or positions) chosen byc.
c.stableInsert(x)nx * log ncSame asc.insert(x), but is guaranteed to not invalidate any ranges.
c.linearInsert(v)ncSame asc.insert(v) but relaxes complexity to linear.
c.stableLinearInsert(v)ncSame asc.stableInsert(v) but relaxes complexity to linear.
c.removeAny()log ncRemoves some element fromc and returns it.
c.stableRemoveAny()log ncSame asc.removeAny(), but is guaranteed to not invalidate any iterators.
c.insertFront(v)log ncInsertsv at the front ofc.
c.stableInsertFront(v)log ncSame asc.insertFront(v), but guarantees no ranges will be invalidated.
c.insertBack(v)log ncInsertsv at the back ofc.
c.stableInsertBack(v)log ncSame asc.insertBack(v), but guarantees no ranges will be invalidated.
c.removeFront()log ncRemoves the element at the front ofc.
c.stableRemoveFront()log ncSame asc.removeFront(), but guarantees no ranges will be invalidated.
c.removeBack()log ncRemoves the value at the back ofc.
c.stableRemoveBack()log ncSame asc.removeBack(), but guarantees no ranges will be invalidated.
c.remove(r)nr * log ncRemoves ranger fromc.
c.stableRemove(r)nr * log ncSame asc.remove(r), but guarantees iterators are not invalidated.
c.linearRemove(r)ncRemoves ranger fromc.
c.stableLinearRemove(r)ncSame asc.linearRemove(r), but guarantees iterators are not invalidated.
c.removeKey(k)log ncRemoves an element fromc by using its keyk. The key's type is defined by the container.

Sourcestd/container/package.d

License:
Distributed under the Boost Software License, Version 1.0.(See accompanying file LICENSE_1_0.txt or copy atboost.org/LICENSE_1_0.txt).
Authors:
Steven Schveighoffer,Andrei Alexandrescu
Copyright © 1999-2026 by theD Language Foundation | Page generated byDdoc on Fri Feb 20 17:58:58 2026

[8]ページ先頭

©2009-2026 Movatter.jp