方式一:使用D标准库中的函数

import std.algorithm; import std.array; import std.conv; import std.functional; import std.stdio;

int[string] array_count_values(T)(T[] array) { int[string] result; foreach (value; array) { if (!is(typeof(value) : int, string)) { throw new Exception("Invalid type: " ~ typeof(value).stringof); } result[value.to!string]++; } return result; }

void main() { int[] array = [1, "hello", 1, "world", "hello"]; writeln(array_count_values(array)); }

方式二:手动实现

import std.algorithm; import std.array; import std.conv; import std.functional; import std.stdio;

int[string] array_count_values(T)(T[] array) { int[string] result; foreach (value; array) { if (!is(typeof(value) : int, string)) { throw new Exception("Invalid type: " ~ typeof(value).stringof); } if (result.canFind(value.to!string)) { result[value.to!string]++; } else { result[value.to!string] = 1; } } return result; }

void main() { int[] array = [1, "hello", 1, "world", "hello"]; writeln(array_count_values(array));

请用D语言实现php的array_count_values函数array_count_valuesarray $array arrayarray_count_values returns an array using the values of array which must be ints or strings as keys and their frequency in array as v

原文地址: https://www.cveoy.top/t/topic/fvcN 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录