Student_info.h
#ifndef GUARD_Student_info #define GUARD_Student_info #include<iostream> #include<vector> #include<string> struct Student_info{ std::string name; double midterm,final; std::vector<double> homework; }; bool compare(const Student_info&,const Student_info&); std::istream& read(std::istream&, Student_info&); std::istream& read_hw(std::istream&,std::vector<double>&); #endif
源文件:
#ifndef GUILDMAIN #define GUILDMAIN #endif #include <iostream> #include <string> #include <vector> #include <algorithm> #include <list> #include <cctype> using namespace std; struct Student_info{ string name; double midterm,final; vector<double> homework; }; //索引版 vector<Student_info> extract_fails(vector<Student_info>& students) { vector<Student_info> fail; vector<Student_info>::size_type i = 0; while(i!= students.size()) { if(fgrade(students[i])) { fail.push_back(students[i]); students.erase(students.begin()+i);//erase 不支持索引,因此取向量的第一个元素,再+i 就变成了第i个元素 }else//删除后,i未改变 自动调整索引会指示向量中的下一个元素,因此不能为下一次循环+1 ++i; } return fail; } //list代替vector list<Student_info> extract_fails(list<Student_info>& students) { list<Student_info> fail; list<Student_info>::iterator iter = students.begin(); while(iter!= students.end()) { if(frage(*iter)) { fail.push_back(*iter); iter = students.erase(iter); }else ++iter; } return fail; } //分割字符串 vector<string> split(const string& s) { vector<string> ret; typedef string::size_type string_size; string_size i = 0; while(i!=s.size()) { while(i!=s.size() && isspace(s[i])) //isspace字符是否空白 ++i; string_size j =i; while(i!=s.size() && !isspace(s[i])) ++j; if(i!=j) { ret.push_back(s.substr(i,j-i)); i = j; } } return ret; } //连接字符串 int main() { vector<Student_info> students; Student_info record; string::size_type maxlen = 0; sort(students.begin(),students.end(),compare); for(vector<Student_info>::size_type i = 0; i!= students.size(); ++i) { cout << students[i].name; students.erase(students.begin()+i); //删除后,i未改变 自动调整索引会指示向量中的下一个元素,因此不能为下一次循环+1 } // 迭代器 for(vector<Student_info>::const_iterator iter = students.begin(); iter != students.end(); ++iter) { cout << iter->name <<endl; } return 0; }
vector 是为快速随即访问而被优化的,
ist可以在容器的任意位置插入和删除
顺序的访问容器的话(递增或递减),list的速度比vector慢
vector支持而list不支持的一个非常重要的操作是索引
list提供了自己的sort() 不能使用std的sort()