迭代器模式

发布时间 2023-11-30 17:08:38作者: 伽澄

[实验任务一]JAVAC++常见数据结构迭代器的使用

信1305班共44名同学,每名同学都有姓名,学号和年龄等属性,分别使用JAVA内置迭代器和C++中标准模板库(STL)实现对同学信息的遍历,要求按照学号从小到大和从大到小两种次序输出学生信息。

实验要求:

1. 搜集并掌握JAVA和C++中常见的数据结构和迭代器的使用方法,例如,vector, list, map和set等;

2. 提交源代码;

3. 注意编程规范。

AVAC++中常见的迭代器:

List接口:

  List是有序的Collection,使用此接口能够精确的控制每个元素插入的位置。用户能够使用索引(元素在List中的位置,类似于数组下标)来访问List中的元素,这类似于Java的数组。和下面要提到的Set不同,List允许有相同的元素。

  除了具有Collection接口必备的iterator()方法外,List还提供一个listIterator()方法,返回一个ListIterator接口,和标准的Iterator接口相比,ListIterator多了一些add()之类的方法,允许添加,删除,设定元素,还能向前或向后遍历。

  实现List接口的常用类有LinkedList,ArrayList,Vector和Stack。

Vector类:

  Vector非常类似ArrayList,但是Vector是同步的。由Vector创建的Iterator,虽然和ArrayList创建的Iterator是同一接口,但是,因为Vector是同步的,当一个Iterator被创建而且正在被使用,另一个线程改变了Vector的状态(例如,添加或删除了一些元素),这时调用Iterator的方法时将抛出ConcurrentModificationException,因此必须捕获该异常。

Set接口:

  Set是一种不包含重复的元素的Collection,即任意的两个元素e1和e2都有e1.equals(e2)=false,Set最多有一个null元素。

  很明显,Set的构造函数有一个约束条件,传入的Collection参数不能包含重复的元素。

  请注意:必须小心操作可变对象(Mutable Object)。如果一个Set中的可变元素改变了自身状态导致Object.equals(Object)=true将导致一些问题。

Map接口:

  请注意,Map没有继承Collection接口,Map提供key到value的映射。一个Map中不能包含相同的key,每个key只能映射一个value。Map接口提供3种集合的视图,Map的内容可以被当作一组key集合,一组value集合,或者一组key-value映射。

 java

Student
package SC18;

public class Student{
    private String id;
    private String name;
    private String age;
    public String getAge() {
        return age;
    }
    public void setAge(String age) {
        this.age = age;
    }
    public Student(){}
    public Student(String id,String name,String age){
        this.id = id;
        this.name = name;
        this.age = age;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String toString() {
        return "学号=" + id + ", 名字=" + name + ", 年龄=" + age;
    }

    public static Student fromString(String s){
        String[] split = s.split(";");
        if(split.length==3){
            return new Student(split[0],split[1],split[2]);
        }else{
            throw new RuntimeException("不能从字符串‘"+s+"’解析出"+Student.class+"类型的对象!");
        }
    }
}

Iterators
package SC18;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;

public class Iterators {

    public static void main(String[] args) {
        InputStream is = Iterators.class.getClassLoader().getResourceAsStream("SC18/Student.txt");
        List<Student> list = getStudents(is);

        System.err.println("学号从小到大:");
        Iterator<Student> iterator = list.iterator();
        while(iterator.hasNext()){
            Student student = iterator.next();
            System.out.println(student);
        }
        System.err.println("学号从大到小:");
        ListIterator<Student> li=list.listIterator();
        for(li=list.listIterator();li.hasNext();) {
            li.next();
        }
        for(;li.hasPrevious();) {
            Student student = li.previous();
            System.out.println(student);
        }
    }

    private static List<Student> getStudents(InputStream is){
        List<Student> list = new LinkedList<>();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        String temp = null;
        try {
            while((temp=reader.readLine())!=null){
                Student student = Student.fromString(temp);
                list.add(student);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }
}

 

c++

#include <string>
#include <vector>
#include <iostream>
#include <fstream>
using namespace std;
struct student
{
    string id;
    string name;
};
void LoadStudent(vector<student>&);
int main()
{
    vector<student> v,v1;
    LoadStudent(v);
    LoadStudent(v1);
    cout<<"学号从小到大:"<<endl;
    for (vector<student>::iterator iter = v.begin(); iter != v.end(); ++iter)
    {
        cout << "学号:" << iter->id << "  姓名:" << iter->name << endl;
    }
    cout<<"***********************"<<endl;
    cout<<"学号从大到小:"<<endl;
    for (vector<student>::reverse_iterator iter1 = v.rbegin(); iter1 != v.rend(); ++iter1)
    {
        cout << "学号:" << iter1->id << "  姓名:" << iter1->name << endl;
    }
    return 0;
}
void LoadStudent(vector<student>& v)
{
    ifstream infile;
    infile.open("E:\\student.txt");
    student s;
    if(!infile)     //判断是否存在ifstream infile
    {
        cout<<"读入文件不存在"<<endl;
    }
    if (infile.is_open())   //判断文件流是否处于打开状态
    {
        while (infile.good()&&!infile.eof())
        {
            infile>>s.id>>s.name;
            v.push_back(s);    //将数据读入到data_vector
        }
    }
    infile.close();
}