Function Pointer as a Parameter & a Member
Get to learn how a function pointer can be used as a parameter and as a member.
We'll cover the following...
Function pointer as a parameter
Let’s design a function that takes an array and returns another array. This function will filter out elements with values less than or equal to zero and multiply the others by ten:
Press + to interact
int[] filterAndConvert(const int[] numbers) {int[] result;foreach (e; numbers) {if (e > 0) { // filtering,immutable newNumber = e * 10; // and conversionresult ~= newNumber;}}return result;}
The following program demonstrates its behavior with randomly generated values:
Press + to interact
import std.stdio;import std.random;int[] filterAndConvert(const int[] numbers) {int[] result;foreach (e; numbers) {if (e > 0) { // filtering,immutable newNumber = e * 10; // and conversionresult ~= newNumber;}}return result;}void main() {int[] numbers;// Random numbersforeach (i; 0 .. 10) {numbers ~= uniform(0, 10) - 5;}writeln("input : ", numbers);writeln("output: ", filterAndConvert(numbers));}
The output contains numbers that are ten times the original numbers, which ...