11.21每日总结

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

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

实验要求:

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

2. 提交源代码;

3. 注意编程规范。

Vector类:

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

Set接口:

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

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

List接口:

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

Map接口:

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

#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(21212121, "AAA", 21, "软工");

    Student *s2 = new Student(21222222, "BBB", 21, "软工");

    Student *s3 = new Student(33333333, "CCC", 21, "软工");

    Student *s4 = new Student(45454545, "DDD", 21, "软工");

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

    }

}

posted @ 2023-11-21 18:06  ME社长  阅读(14)  评论(0)    收藏  举报