What is the swapAt function in D

Overview

The D offers a large standard library. It has a lot of functions to help us pull one or two out of the shelf.

In this shot, we’ll look at a function from the mutation library, which carries out a basic sort operation on the provided variable. The swapAt() function is used to swap an element in an array or tuple with another using its index in such array.

This function locates the indexes provided in an array and swap the elements at the two index positions.

Syntax

swapAt(array,array_a_index,array_2_index)

Parameters

This function requires the following parameters:

  • array: The array whose elements are to swap positions.
  • array_index_a: This is the index of the value in one of the two arrays to be swapped.
  • array_index_b: This is the index of the value in the second array amongst the two values to be swapped.

Return value

This function returns void, meaning it returns no value.

Example

import std.stdio;
import std.algorithm.mutation;
void main(){
//declare variables
int [5] ref_array = [1,2,3,4,5];
//carry out a swap
swapAt(ref_array, 2,3);
writeln("This is ref_array after the first swap : ",ref_array);
//swap again
ref_array.swapAt(0,1);
writeln("This is ref_array after the second swap : ",ref_array);
}

Explanation

  • Line 1 and 2: We import some modules from the standard library.
  • Line 4: We start the main function.
  • Line 6: We declare a variable ref_array.
  • Line 8: We use the swapAt() function to swap elements at index 2 and 3 in the array.
  • Line 9: We write the array to the output once more to check if the swap happened. We repeat this process in lines 11 and 12.

Free Resources