每日总结
软件设计模式 迭代器:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Iterator {
public:
virtual void init(int n) = 0;
virtual void zxSelect() = 0;
virtual void dxSelect() = 0;
};
class Student {
public:
string name;
string num;
string age;
string toString() {
return "该学生的学号为:" + num + ",姓名为:" + name + ",年龄为" + age;
}
Student(string name, string num, string age) {
this->name = name;
this->num = num;
this->age = age;
};
};
class ListIterator :public Iterator {
public:
vector<Student>* list;
void zxSelect() {
cout << "按照学号正序输出:" << endl;
for (int i = 0; i < list->size(); i++) {
cout << list->at(i).toString() << endl;
}
}
void dxSelect() {
cout << "按照学号倒序输出:" << endl;
for (int i = list->size() - 1; i >= 0; i--) {
cout << list->at(i).toString() << endl;
}
}
void init(int n) {
this->list = new vector<Student>;
for (int i = 1; i <= n; i++) {
int a = i;
int b = 2019411 + i;
int c = i + 20;
string name = "张" + to_string(a);
string num = to_string(b);
string age = to_string(c);
Student stu = Student(name, num, age);
this->list->push_back(stu);
}
}
};
int main() {
Iterator* iter;
iter = new ListIterator();
iter->init(5);
iter->zxSelect();
cout << "*************************************" << endl;
iter->dxSelect();
}