Content deleted Content added
m Remove outdated warning header |
No edit summary |
||
Line 11:
double& operator[](int i) { return data[i]; }
};
#include <iostream>
int main() {
vector v(3);
for (int i = 0; i < v.size; i++) v[i] = i + 1;
for (int i = 0; i < v.size; i++) std::cout << v[i] << "\n";
return 0;
}
</syntaxhighlight>
=== C
Indexers are implemented through the get and set [[Mutator method|accessor]]s for the {{C_sharp|operator[]}}. They are similar to [[Property (programming)|properties]], but differ by not being [[Static method|static]], and the fact that indexers' accessors take parameters. The get and set accessors are called as methods using the parameter list of the indexer declaration, but the set accessor still has the implicit {{C_sharp|value}} parameter.
Line 27 ⟶ 29:
public class Vector
{
private double[]
public Vector(int n) { data = new double[n]; }▼
public Vector(int
{
}
public int Size => _data.Length;
public double this[int i]
{
get => _data[i];
set => _data[i] = value;
}
public static void Main()
{
var
for (
for (var i = 0; i < vector.Size; i++)
System.Console.WriteLine(vector[i]);
}
}
Line 102 ⟶ 116:
<syntaxhighlight lang="php">
<?php
class Vector implements ArrayAccess
{ function __construct(int $n) {
$this->size = $n;
$this->data = array_fill(0, $n, 0);
}
public function offsetGet($offset): mixed {
return $this->data[$offset];
}
public function offsetSet($offset, $value): void {
$this->data[$offset] = $value;
}
public function offsetExists($offset): bool {}
public function offsetUnset($offset): void {}
}
$
for ($i = 0; $i < $v->size; $i++) $v[$i] = $i + 1;▼
for ($i = 0; $i < $v->size; $i++) print "{$v[$i]}\n";▼
?>
</syntaxhighlight>
Line 126 ⟶ 147:
<syntaxhighlight lang="python">
import array
class Vector(object):
def __init__(self, n: int):
self.size = n
self.data = array.array("d", [0.0] * n)
def __getitem__(self, i): return self.data[i]▼
def __setitem__(self, i, value): self.data[i] = value▼
v = Vector(3)▼
return self.data[i]
for i in range(v.size): v[i] = i + 1▼
for i in range(v.size): print(v[i])▼
self.data[i] = value
vector[i] = i + 1
print(vector[i])
</syntaxhighlight>
|