如何有条件地从D中的数组创建类参数数组?

时间:2018-08-30 02:39:20

标签: 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
}

2 个答案:

答案 0 :(得分:1)

std.algorithm支持您的工作

import std.algorithm, std.array;
auto kids = classroom.values
    .filter!(student => student.grade == 5)
    .array;

如果要一次为每个年级执行此操作,则需要先排序然后再按块排序,如下所示:

classroom.values
    .sort!((x, y) => x.grade < y.grade)
    .chunkBy((x, y) => x.grade == y.grade)

哪个会给您提供一系列[同一年级的学生范围]。

答案 1 :(得分:1)

您所需要的只是借助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
}