24.12.02

实验18:迭代器模式

本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:

1、理解迭代器模式的动机,掌握该模式的结构;

2、能够利用迭代器模式解决实际问题。

[实验任务一]JAVAC++常见数据结构迭代器的使用

信1305班共44名同学,每名同学都有姓名,学号和年龄等属性,分别使用JAVA内置迭代器和C++中标准模板库(STL)实现对同学信息的遍历,要求按照学号从小到大和从大到小两种次序输出学生信息。

实验要求:

1. 搜集并掌握JAVA和C++中常见的数据结构和迭代器的使用方法,例如,vector, list, map和set等;

2. 提交源代码;

3. 注意编程规范。

 

Java代码:

import java.util.*;

 

class Student {

    private String name;

    private String id;

    private int age;

 

    public Student(String name, String id, int age) {

        this.name = name;

        this.id = id;

        this.age = age;

    }

 

    public String getId() {

        return id;

    }

 

    @Override

    public String toString() {

        return "Student{name='" + name + "', id='" + id + "', age=" + age + '}';

    }

}

 

public class StudentSort {

    public static void main(String[] args) {

        List<Student> students = new ArrayList<>();

        // 假设数据已添加

        students.add(new Student("Alice", "13051001", 20));

        students.add(new Student("Bob", "13051003", 21));

        students.add(new Student("Charlie", "13051002", 22));

 

        // 按学号从小到大排序

        students.sort(Comparator.comparing(Student::getId));

        System.out.println("按学号从小到大:");

        Iterator<Student> iterator = students.iterator();

        while (iterator.hasNext()) {

            System.out.println(iterator.next());

        }

 

        // 按学号从大到小排序

        students.sort(Comparator.comparing(Student::getId).reversed());

        System.out.println("按学号从大到小:");

        iterator = students.iterator();

        while (iterator.hasNext()) {

            System.out.println(iterator.next());

        }

    }

}

 

C++代码:

 

#include <iostream>

#include <vector>

#include <algorithm>

#include <string>

 

using namespace std;

 

struct Student {

    string name;

    string id;

    int age;

 

    friend ostream& operator<<(ostream& os, const Student& s) {

        os << "Student{name='" << s.name << "', id='" << s.id << "', age=" << s.age << "}";

        return os;

    }

};

 

int main() {

    vector<Student> students = {

        {"Alice", "13051001", 20},

        {"Bob", "13051003", 21},

        {"Charlie", "13051002", 22}

    };

 

    // 按学号从小到大排序

    sort(students.begin(), students.end(), [](const Student& a, const Student& b) {

        return a.id < b.id;

    });

 

    cout << "按学号从小到大:" << endl;

    for (const auto& student : students) {

        cout << student << endl;

    }

 

    // 按学号从大到小排序

    sort(students.begin(), students.end(), [](const Student& a, const Student& b) {

        return a.id > b.id;

    });

 

    cout << "按学号从大到小:" << endl;

    for (const auto& student : students) {

        cout << student << endl;

    }

 

    return 0;

}

 

posted on 2024-12-02 16:14  Daniel350  阅读(8)  评论(0)    收藏  举报