实验

JAVA
import java.util.*;

class Student {
    String name;
    int id;
    int age;

    public Student(String name, int id, int age) {
        this.name = name;
        this.id = id;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Name: " + name + ", ID: " + id + ", Age: " + age;
    }
}

public class StudentIterator {
    public static void main(String[] args) {
        List<Student> students = new ArrayList<>();
        students.add(new Student("Alice", 1001, 20));
        students.add(new Student("Bob", 1003, 22));
        students.add(new Student("Charlie", 1002, 21));

        // 按学号从小到大排序
        students.sort(Comparator.comparingInt(s -> s.id));
        System.out.println("按学号从小到大:");
        for (Student student : students) {
            System.out.println(student);
        }

        // 按学号从大到小排序
        students.sort((s1, s2) -> Integer.compare(s2.id, s1.id));
        System.out.println("按学号从大到小:");
        for (Student student : students) {
            System.out.println(student);
        }
    }
}

C++

#include <iostream>
#include <vector>
#include <algorithm>

struct Student {
        std::string name;
        int id;
        int age;

        Student(std::string n, int i, int a) : name(n), id(i), age(a) {}

        void print() const {
        std::cout << "Name: " << name << ", ID: " << id << ", Age: " << age << std::endl;
        }
        };

        int main() {
        std::vector<Student> students = {
        {"Alice", 1001, 20},
        {"Bob", 1003, 22},
        {"Charlie", 1002, 21}
        };

        // 按学号从小到大排序
        std::sort(students.begin(), students.end(), [](const Student &a, const Student &b) {
        return a.id < b.id;
        });
        std::cout << "按学号从小到大:" << std::endl;
        for (const auto &student : students) {
        student.print();
        }

        // 按学号从大到小排序
        std::sort(students.begin(), students.end(), [](const Student &a, const Student &b) {
        return a.id > b.id;
        });
        std::cout << "按学号从大到小:" << std::endl;
        for (const auto &student : students) {
        student.print();
        }

        return 0;
        }

 

posted @ 2024-11-18 08:35  KuanDong24  阅读(3)  评论(0编辑  收藏  举报