1. 程式人生 > 其它 >軟體設計-迭代器模式

軟體設計-迭代器模式

JAVA和C++常見資料結構迭代器的使用
信1305班共44名同學,每名同學都有姓名,學號和年齡等屬性,分別使用JAVA內建迭代器和C++中標準模板庫(STL)實現對同學資訊的遍歷,要求按照學號從小到大和從大到小兩種次序輸出學生資訊。

原始碼

Java內建迭代器

package rjsj.no18;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

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; } @Override public String toString() { return "Student{" + "姓名='" + name + '\'' + ", 學號=" + sid + ", 年齡=" + age + '}'; } @Override
public int compareTo(Student o) { if (this.sid > o.sid){ return -1; } else if (this.sid < o.sid){ return 1; } else { return 0; } } } class IteratorDemo { public static void main(String[] args) { Student student1
= new Student("張三",20193885,21); Student student2 = new Student("李四",20201456,20); Student student3 = new Student("王五",20184655,23); Student student4 = new Student("趙六",20191242,22); Student student5 = new Student("李七",20213256,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()); } } }

C++

#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();
    }
}

執行結果