您的位置:首页 > 其它

STL 实践(for_each() getline sort random_shuffle的使用)

2007-06-04 13:30 519 查看

#include <iostream>


#include <string>


#include <fstream>


#include <vector>


#include <algorithm>




using namespace std;






struct Review ...{


std::string title;


int rating;


};




bool operator<(const Review & r1, const Review & r2);


bool worseThan(const Review & r1, const Review & r2);


//bool FillReview(Review & rr);


void ShowReview(const Review & rr);


bool FillReview(Review & rr, ifstream &fin);






int main()




...{






ifstream fin;


fin.open("test.txt");


if(!fin.is_open())




...{


cerr<<"can't open the file!"<< endl;


return 0;


}




vector<Review> books;


Review temp;


while (FillReview(temp,fin))


books.push_back(temp);




fin.close();


cout << "Thank you. You entered the following "


<< books.size() << " ratings: "


<< "Rating Book ";


for_each(books.begin(), books.end(), ShowReview);




sort(books.begin(), books.end());


cout << "Sorted by title: Rating Book ";


for_each(books.begin(), books.end(), ShowReview);




sort(books.begin(), books.end(), worseThan);


cout << "Sorted by rating: Rating Book ";


for_each(books.begin(), books.end(), ShowReview);




random_shuffle(books.begin(), books.end());


cout << "After shuffling: Rating Book ";


for_each(books.begin(), books.end(), ShowReview);


cout << "Bye. ";


return 0;


}




bool operator<(const Review & r1, const Review & r2)




...{


if (r1.title < r2.title)


return true;


else if (r1.title == r2.title && r1.rating < r2.rating)


return true;


else


return false;


}




bool worseThan(const Review & r1, const Review & r2)




...{


if (r1.rating < r2.rating)


return true;


else


return false;


}




bool FillReview(Review & rr)




...{


std::cout << "Enter book title (quit to quit): ";


std::getline(std::cin,rr.title);


if (rr.title == "quit")


return false;


std::cout << "Enter book rating: ";


std::cin >> rr.rating;


if (!std::cin)


return false;


std::cin.get();


return true;


}




void ShowReview(const Review & rr)




...{


std::cout << rr.rating << " " << rr.title << std::endl;


}




bool FillReview(Review & rr,ifstream &fin)




...{


if(!fin)


return false;


getline(fin,rr.title,';');


if(rr.title == "")


return false;


string rating;






getline(fin,rating,';');


rr.rating = atoi(rating.c_str());




return true;


}

for_each()函数可用来替换for循环
vector<Review>::iterator pr;
for(pr = books.begin(); pr!=books.end(); pr++)
showReview(*pr);

替换为:
for_each(book.begin(),book.end(),ShowReview);

ShowReview原型
void ShowReview(const Review& rr)
最后一个参数是函数对象,它不改变参数的值。

test.txt

abc;100;bdf;39;ffff;453;zzz;789;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐