d - 如何从 D 中的数组有条件地创建类参数数组?
问题描述
假设我有一个包含一堆类实例的关联数组。我想找到一种惯用的 D 方法来创建一个数组(或范围),该数组(或范围)包含属于数组中的类实例的属性,这些属性意味着一些布尔标准。
请参阅下面的示例,在这种情况下,我想创建一个数组或范围,其中包含五年级学生的年龄。
我知道如何使用循环和条件来做到这一点,但如果在 D 中有一个内置函数或惯用的方式来做到这一点,那将非常有帮助。
import std.stdio;
class Student {
private:
uint grade;
uint age;
uint year;
public:
this(uint g, uint a, uint y) {
grade = g;
age = a;
year = y;
}
uint getAge() {
return age;
}
uint getGrade() {
return grade;
}
uint getYear() {
return year;
}
}
void main() {
Student[uint] classroom;
Student s1 = new Student(1, 5, 2);
Student s2 = new Student(2, 6, 1);
Student s3 = new Student(3, 7, 2);
Student s4 = new Student(4, 8, 9);
classroom[1] = s1;
classroom[2] = s1;
classroom[3] = s1;
classroom[4] = s1;
// I want to generate an array or range here containing the age of students who are in the X'th grade
}
解决方案
std.algorithm 支持您:
import std.algorithm, std.array;
auto kids = classroom.values
.filter!(student => student.grade == 5)
.array;
如果您想一次为每个年级执行此操作,则需要先排序,然后再进行 chunkBy,例如:
classroom.values
.sort!((x, y) => x.grade < y.grade)
.chunkBy((x, y) => x.grade == y.grade)
这为您提供了一系列[具有相同成绩的学生范围]。
推荐阅读
- android - Android:如何使用 Android Camera API 检测视频大小
- flutter - Flutter BLoC 状态管理
- sql - 从 Postgres 中的多维数组中插入行
- javascript - Angular Material - 在第一个响应式网格列中开始内容
- pyspark - 在pyspark中逐行比较两个数据框
- java - java中的模10 ^ 9 + 7
- arrays - 将 CSV 文件转换为数组会消耗大量内存
- html - 无论实际值如何,HTML 输入类型“tel”属性“autocomplete”都停留在“tel-national”上
- c++ - 启用优化时 C++ 模板的行为不同(发布)
- javascript - SyntaxError:导入声明可能只出现在模块的顶层,如何解决?