迭代器模式
信1305班共44名同学,每名同学都有姓名,学号和年龄等属性,分别使用JAVA内置迭代器和C++中标准模板库(STL)实现对同学信息的遍历,要求按照学号从小到大和从大到小两种次序输出学生信息。
1. 搜集并掌握JAVA和C++中常见的数据结构和迭代器的使用方法,例如,vector, list, map和set等;
2. 提交源代码;
3. 注意编程规范。
Java代码:
Student.java
import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; class Student { String name; int studentID; int age; public Student(String name, int studentID, int age) { this.name = name; this.studentID = studentID; this.age = age; } }
StudentList.java
import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; public class StudentList { public static void main(String[] args) { List<Student> studentList = new ArrayList<>(); // 从学号20213000开始生成学生对象并添加到列表,年龄都设置成20岁 int startingStudentID = 20213000; for (int i = 0; i < 44; i++) { studentList.add(new Student("学生" + (i + 1), startingStudentID + i, 20)); } // 按学号升序排序 Collections.sort(studentList, (s1, s2) -> Integer.compare(s1.studentID, s2.studentID)); System.out.println("按学号从小到大:"); printStudentInfo(studentList.iterator()); // 按学号降序排序 Collections.sort(studentList, (s1, s2) -> Integer.compare(s2.studentID, s1.studentID)); System.out.println("\n按学号从大到小:"); printStudentInfo(studentList.iterator()); } private static void printStudentInfo(Iterator<Student> iterator) { while (iterator.hasNext()) { Student student = iterator.next(); System.out.println("姓名: " + student.name + ",学号: " + student.studentID + ",年龄: " + student.age); } } }
C++
#include <iostream> #include <vector> #include <algorithm> #include <string> class Student { public: std::string name; int studentID; int age; Student(std::string n, int id, int a) : name(n), studentID(id), age(a) {} }; bool compareByIDAsc(const Student& s1, const Student& s2) { return s1.studentID < s2.studentID; } bool compareByIDDesc(const Student& s1, const Student& s2) { return s1.studentID > s2.studentID; } int main() { std::vector<Student> studentList; // 从学号20213000开始生成学生对象并添加到向量,年龄都设置成20岁 int startingStudentID = 20213000; for (int i = 0; i < 44; i++) { studentList.push_back(Student("学生" + std::to_string(i + 1), startingStudentID + i, 20)); } // 按学号升序排序 std::sort(studentList.begin(), studentList.end(), compareByIDAsc); std::cout << "按学号从小到大:" << std::endl; for (const auto& student : studentList) { std::cout << "姓名: " << student.name << ",学号: " << student.studentID << ",年龄: " << student.age << std::endl; } // 按学号降序排序 std::sort(studentList.begin(), studentList.end(), compareByIDDesc); std::cout << "\n按学号从大到小:" << std::endl; for (const auto& student : studentList) { std::cout << "姓名: " << student.name << ",学号: " << student.studentID << ",年龄: " << student.age << std::endl; } return 0; }
标签:studentID,java,报告,int,util,studentList,Student,今日 From: https://www.cnblogs.com/zjq164/p/17843180.html