Java
//Student.java
package shiyan18;
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.java
package shiyan18;
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("shiyan18/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();
}