Generic swap: Difference between revisions

Content added Content deleted
(→‎{{header|Pascal}}: add example)
(Better D entry)
Line 253: Line 253:


=={{header|D}}==
=={{header|D}}==
<lang d>import std.algorithm: swap; // from Phobos standard library
The solution for D is quite similar to that for C++:


// The D solution uses templates and it's similar to the C++ one:
<lang d>void swap(T)(ref T left, ref T right) {
void mySwap(T)(ref T left, ref T right) {
auto temp = left;
left = right;
auto temp = left;
right = temp;
left = right;
right = temp;
}

void main() {
import std.stdio;

int[] a = [10, 20];
writeln(a);

// The std.algorithm standard library module
// contains a generic swap:
swap(a[0], a[1]);
writeln(a);

// Using mySwap:
mySwap(a[0], a[1]);
writeln(a);
}</lang>
}</lang>
{{out}}
The std.algorithm standard library module contains a generic swap.
<pre>[10, 20]
[20, 10]
[10, 20]</pre>


=={{header|dc}}==
=={{header|dc}}==