完成设计模式实验十八,以下为今日实验内容:
实验18:迭代器模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解迭代器模式的动机,掌握该模式的结构;
2、能够利用迭代器模式解决实际问题。
[实验任务一]:JAVA和C++常见数据结构迭代器的使用
信1305班共44名同学,每名同学都有姓名,学号和年龄等属性,分别使用JAVA内置迭代器和C++中标准模板库(STL)实现对同学信息的遍历,要求按照学号从小到大和从大到小两种次序输出学生信息。
实验要求:
1. 搜集并掌握JAVA和C++中常见的数据结构和迭代器的使用方法,例如,vector, list, map和set等;
在JAVA中,可以使用ArrayList、LinkedList、HashMap、TreeMap、HashSet、TreeSet等集合类来存储数据,并使用内置的迭代器进行遍历。
在C++中,可以使用std::vector、std::list、std::map、std::set等STL容器来存储数据,并使用迭代器进行遍历。
2. 提交源代码;
- import java.util.*;
// 学生类
class Student {
String name;
String id;
int age;
public Student(String name, String id, int age) {
this.name = name;
this.id = id;
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", id='" + id + '\'' +
", age=" + age +
'}';
}
}
public class IteratorDemo {
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
students.add(new Student("Alice", "001", 20));
students.add(new Student("Bob", "002", 22));
students.add(new Student("Charlie", "003", 21));
// 按学号从小到大遍历
Collections.sort(students, Comparator.comparing(s -> s.id));
for (Student student : students) {
System.out.println(student);
}
// 按学号从大到小遍历
Collections.sort(students, Comparator.comparing(s -> s.id).reversed());
for (Student student : students) {
System.out.println(student);
}
}
}
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
// 学生类
class Student {
public:
std::string name;
std::string id;
int age;
Student(std::string name, std::string id, int age) : name(name), id(id), age(age) {}
friend bool operator<(const Student& a, const Student& b) {
return a.id < b.id;
}
};
int main() {
std::vector<Student> students;
students.emplace_back("Alice", "001", 20);
students.emplace_back("Bob", "002", 22);
students.emplace_back("Charlie", "003", 21);
// 按学号从小到大遍历
std::sort(students.begin(), students.end());
for (const auto& student : students) {
std::cout << student.name << " " << student.id << " " << student.age << std::endl;
}
// 按学号从大到小遍历
std::sort(students.begin(), students.end(), std::greater<Student>());
for (const auto& student : students) {
std::cout << student.name << " " << student.id << " " << student.age << std::endl;
}
return 0;
}