程序设计实验6
实验任务1
实验任务2
实验任务3
实验任务4
1 #pragma once 2 #include<iostream> 3 #include<stdexcept> 4 #include<iomanip> 5 using namespace std; 6 template<typename T> 7 class Vector { 8 private: 9 int size; 10 T* ptr; 11 public: 12 Vector(int size, int value = 0) :size{ size } { 13 if (size < 0) { 14 throw length_error("negative size"); 15 } 16 ptr = new T[size]; 17 for (int i = 0; i < size; i++) { 18 ptr[i] = value; 19 } 20 } 21 int get_size()const { return size; } 22 T& at(int index)const { 23 if (index < 0 || index >= size) throw out_of_range("index out of range"); 24 return ptr[index]; 25 } 26 T& operator[](int index)const { 27 if (index < 0 || index >= size) throw out_of_range("index out of range"); 28 return ptr[index]; 29 } 30 }; 31 template<typename T1> 32 void output(const Vector<T1>& v) { 33 for (int i = 0; i < v.get_size();i++) { 34 cout << v[i] <<", "; 35 } 36 cout << endl; 37 }
实验任务5
1 #include<iostream> 2 #include<fstream> 3 #include<algorithm> 4 #include<vector> 5 #include<iomanip> 6 #include<string> 7 using namespace std; 8 struct stu 9 { 10 string id; 11 string name; 12 string major; 13 int score; 14 stu(string id,string name,string major,int score):id{id},name{name},major{major},score{score}{} 15 }; 16 bool compare(stu x, stu y) { 17 if(x.major!=y.major) 18 return x.major < y.major; 19 else{ 20 return x.score > y.score; 21 } 22 } 23 int main() { 24 ifstream input("data5.txt"); 25 if (!input.is_open()) { 26 cout << "无法加载文件中的数据" << endl; 27 return 0; 28 } 29 string id, name, major; 30 int score; 31 vector<stu> v; 32 while (input >> id >> name >> major >> score) { 33 v.push_back(stu(id, name, major, score)); 34 } 35 input.close(); 36 sort(v.begin(), v.end(), compare); 37 ofstream output("ans5.txt"); 38 if (!output.is_open()) { 39 cout << "文件加载失败" << endl; 40 } 41 for (auto i : v) { 42 cout << setiosflags(ios_base::left); 43 cout << setw(10) << i.id << setw(10) << i.name << setw(10) << i.major << setw(10) << i.score << endl; 44 output << i.id << " " << i.name << " " << i.major << " " << i.score << endl; 45 } 46 output.close(); 47 return 0; 48 }