迭代器模式--C++模式实现

具体代码

#include<algorithm>
#include<vector>
#include<fstream>
#include<string>
#include<istream>
#include<sstream>
#include<iostream>

using namespace std;

struct Student{
	string id;
	string name;
	string age;
};

void ReadStudentInformation(vector<Student> &);

int main() {//主函数,实现学号排序
	vector<Student> v, v1;
	ReadStudentInformation(v);
	ReadStudentInformation(v1);

	cout << "学号从小到大排列:" << endl;
	for (vector<Student>::iterator iter = v.begin(); iter != v.end(); ++iter) {
		cout << "学号: " << iter->id << " 姓名: " << iter->name <<" 年龄: " << iter->age << endl;
	}

	cout << "学号从大到小排列:" << endl;
	for (vector<Student>::reverse_iterator iter = v.rbegin(); iter != v.rend(); ++iter) {
		cout << "学号: " << iter->id << " 姓名:" << iter->name <<" 年龄: " << iter->age << endl;
	}

	return 0;
}

void ReadStudentInformation(vector<Student>& v) {
	ifstream file;
	file.open("F:\\Data\\Student.txt");

	Student student;
	if (!file) {
		cout << "想要读取的文件不存在" << endl;
	}

	if (file.is_open()) {//文件已经处于打开状态,可进行数据的读取
		string line;
		while (getline(file,line)) {
			stringstream ss(line);
			string tmp;
			string id, name, age;

			int i = 0;

			while (getline(ss, tmp, ',')) {
				if (i == 0) id = tmp;
				if (i == 1) name = tmp;
				if (i == 2) age = tmp;
				i++;
			}
			student.id = id;
			student.name = name;
			student.age = age;
			cout << student.id << endl;
			cout << student.name << endl;
			cout << student.age << endl;
			v.push_back(student);
			cout << "student" << endl;
			cout<<student.id<<" "<<student.name<<" "<<student.age<<endl;
		}

	}

	file.close();

}

运行结果

posted @ 2023-11-20 10:28  yesyes1  阅读(5)  评论(0编辑  收藏  举报