[实验任务一]:JAVA和C++常见数据结构迭代器的使用
信1305班共44名同学,每名同学都有姓名,学号和年龄等属性,分别使用JAVA内置迭代器和C++中标准模板库(STL)实现对同学信息的遍历,要求按照学号从小到大和从大到小两种次序输出学生信息。
实验要求:
1. 搜集并掌握JAVA和C++中常见的数据结构和迭代器的使用方法,例如,vector, list, map和set等;
2. 提交源代码;
3. 注意编程规范。
#include<iostream> #include <vector> #include<algorithm> using namespace std; class Student{ public: long studentid; string name; int age; string major; public: Student(long studentid, string name, int age, string major) { this->studentid = studentid; this->name = name; this->age = age; this->major = major; } void show(){ cout<<"姓名: "<<this->name<<"\t学号: "<<this->studentid <<"\t年龄: "<< this->age<< "\t专业: " << this->major<<endl; } }; bool compMax(Student *a,Student *b){ if (a->studentid> b->studentid) return true; else return false; } bool compMin(Student *a,Student *b){ if (a->studentid< b->studentid) return true; else return false; } int main(){ Student *s1 = new Student(20193288, "张三", 19, "土木"); Student *s2 = new Student(20193999, "李四", 21, "经管"); Student *s3 = new Student(20196654, "王五", 22, "软工"); Student *s4 = new Student(20193367, "赵六", 20, "机械"); vector<Student*> vec; vec.push_back(s1); vec.push_back(s2); vec.push_back(s3); vec.push_back(s4); cout<<"按照学号从大到小输出: "<<endl; vector<Student*>::iterator it; sort(vec.begin(), vec.end(),compMax); for(it=vec.begin();it!=vec.end();it++){ (*it)->show(); } cout<<"-----------------------------------------------------------------"<<endl; cout<<"按照学号从小到大输出: "<<endl; sort(vec.begin(), vec.end(),compMin); for(it=vec.begin();it!=vec.end();it++){ (*it)->show(); } }
public class Student implements Comparable<Student>{ private String name; private int sid; private int age; public Student(String name, int sid, int age) { this.name = name; this.sid = sid; this.age = age; } public String toString() { return "Student{" + "姓名='" + name + '\'' + ", 学号=" + sid + ", 年龄=" + age + '}'; } public int compareTo(Student o) { if (this.sid > o.sid){ return -1; } else if (this.sid < o.sid){ return 1; } else { return 0; } } }
import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; public class IteratorDemo { public static void main(String[] args) { Student student1 = new Student("张三",20211145,21); Student student2 = new Student("李四",20215142,20); Student student3 = new Student("王五",20211919,23); Student student4 = new Student("赵六",20218108,22); Student student5 = new Student("李七",20214121,19); List<Student> list = new ArrayList<Student>(); list.add(student1); list.add(student2); list.add(student3); list.add(student4); list.add(student5); Collections.sort(list); System.out.println("按学号排序输出:"); Iterator i = list.iterator(); while (i.hasNext()){ System.out.println(i.next().toString()); } } }
标签:name,十八,list,实验,vec,Student,sid,new From: https://www.cnblogs.com/usadingzhen/p/17843162.html