实验18:迭代器模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解迭代器模式的动机,掌握该模式的结构;
2、能够利用迭代器模式解决实际问题。
[实验任务]:JAVA和C++常见数据结构迭代器的使用
信1305班共44名同学,每名同学都有姓名,学号和年龄等属性,分别使用JAVA内置迭代器和C++中标准模板库(STL)实现对同学信息的遍历,要求按照学号从小到大和从大到小两种次序输出学生信息。
实验要求:
搜集并掌握JAVA和C++中常见的数据结构和迭代器的使用方法,例如vector, list, map和set等;
代码
import java.util.*;class Student
{int id;String name;int age;public Student(int id, String name, int age){this.id = id;this.name = name;this.age = age;}
}public class List_Iterator
{public static void sortById(List list){Iterator<Student> sIterator = list.iterator();while (sIterator.hasNext()){Student student = sIterator.next();System.out.println("学号: " + student.id + ", 姓名: " + student.name + ", 年龄: " + student.age);}}public static void main(String[] args){List<Student> studentList = new ArrayList<>();studentList.add(new Student(20213971, "门殿宇", 20));studentList.add(new Student(20211234, "张三", 20));studentList.add(new Student(20214352, "李四", 20));studentList.add(new Student(20210123, "王五", 20));studentList.add(new Student(20214444, "小明", 20));studentList.add(new Student(20215423, "小李", 20));studentList.add(new Student(20217462, "小王", 20));studentList.add(new Student(20212344, "小张", 20));studentList.add(new Student(20213888, "小刘", 20));studentList.add(new Student(20219999, "小马", 20));//按学号升序排序Collections.sort(studentList, Comparator.comparingInt(student -> student.id));//用迭代器打印System.out.println("按学号升序:");sortById(studentList);Collections.reverse(studentList);//迭代器打印降序学号System.out.println("\n按学号降序:");sortById(studentList);}
}
#include <iostream>
#include <vector>
#include <algorithm>using namespace std;// 自定义数据类型
class Student
{
public:int id;string name;int age;public:Student(int id, string name, int age) : id(id), name(name), age(age){}
};// 比较函数,按学号升序排序
bool compareByIdUp(const Student &a, const Student &b)
{return a.id < b.id;
}//按学号降序排序
bool compareByIdDown(const Student &a, const Student &b)
{return a.id > b.id;
}// 打印学生信息
void printStudentInfo(vector<Student> &v)
{for (vector<Student>::iterator it = v.begin(); it != v.end(); it++){cout << "学号:" << (*it).id << " 姓名:" << (*it).name << " 年龄:" << (*it).age << endl;}cout << endl;
}int main()
{vector<Student> students;students.emplace_back(20213971, "门殿宇", 20);students.emplace_back(20211234, "张三", 20);students.emplace_back(20214352, "李四", 20);students.emplace_back(20210123, "王五", 20);students.emplace_back(20214444, "小明", 20);students.emplace_back(20215423, "小李", 20);students.emplace_back(20217462, "小王", 20);students.emplace_back(20212344, "小张", 20);students.emplace_back(20213888, "小刘", 20);students.emplace_back(20219999, "小马", 20);// 使用 sort 函数和比较函数按学号升序排序sort(students.begin(), students.end(), compareByIdUp);cout << "按学号升序排列" << endl;// 打印排序后的学生信息printStudentInfo(students);// 使用 sort 函数和比较函数按学号降序排序sort(students.begin(), students.end(), compareByIdDown);cout << "按学号降序排列" << endl;// 打印排序后的学生信息printStudentInfo(students);return 0;
}
运行效果