如何从D中的数组有条件地创建类参数数组?
假设我有一个关联数组,其中包含一组类实例。我想找到一种惯用的方法来创建一个数组(或范围),其中包含属于数组中表示一些布尔条件的类实例的属性 请参见下面的示例,在本例中,我希望创建一个数组或范围,其中包含五年级学生的年龄 我知道如何使用循环和条件实现这一点,但如果在D中有内置函数或惯用方法实现这一点,那将非常有用如何从D中的数组有条件地创建类参数数组?,d,D,假设我有一个关联数组,其中包含一组类实例。我想找到一种惯用的方法来创建一个数组(或范围),其中包含属于数组中表示一些布尔条件的类实例的属性 请参见下面的示例,在本例中,我希望创建一个数组或范围,其中包含五年级学生的年龄 我知道如何使用循环和条件实现这一点,但如果在D中有内置函数或惯用方法实现这一点,那将非常有用 import std.stdio; class Student { private: uint grade; uint age;
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)
class.values
分类((x,y)=>x.gradex.grade==y.grade)
这为您提供了一系列[同年级学生的范围]。您只需要借助std.algorithm模块进行一点函数编程:
import std.stdio;
import std.algorithm, std.array;
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] = s2;
classroom[3] = s3;
classroom[4] = s4;
classroom[5] = new Student(3, 8, 3);
// I want to generate an array or range here containing the age of students who are in the X'th grade
uint grd = 3;
auto ages = classroom.values
.filter!(student => student.getGrade() == grd)
.map!(student => student.getAge());
writeln(ages);
uint[] arr = ages.array; // if you need to turn the range into an array
writeln(arr); // prints the same as above
}
谢谢,但这两个例子都返回了一系列的学生。我想要的不是一系列学生,而是属于这些学生的一系列财产,例如这些学生的年龄范围。