【Accelerated C++】读书笔记(二)

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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值