/*
*STL中排序相关函数:
* 1)operator<()为全排序;
* 2)WorseThan()为完整弱排序;
*/
#include <iostream>
#include<string>
#include<vector>
#include<algorithm>
// 结构体在c++中和类一样对待,他们唯一的区别,就是缺省情况下,struct中的所有成员都是public的,class中的所有成员都是private的
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);
int main() {
using namespace std;
vector<Review> books;
Review temp;
while (FillReview(temp))
books.push_back(temp);
cout << "Thank you. You entered the following" << books.size()
<< "ratings: \n" << "Rating \t Book\n";
for_each(books.begin(), books.end(), ShowReview);
sort(books.begin(), books.end());
cout << "Sorted by title: \n Rating \t book \ n";
for_each(books.begin(), books.end(), ShowReview);
sort(books.begin(), books.end(), worseThan);
cout << "Sorted by rating: \n Rating \t Book \n";
for_each(books.begin(), books.end(), ShowReview);
// Random_shuffle()接收两个指定区间的迭代器参数,并随机排列该区域中的元素;
random_shuffle(books.begin(), books.end());
cout << "After shuffling: \n Rating \t Book \n";
for_each(books.begin(), books.end(), ShowReview);
cout << "Bye. \n";
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 << "\t" << rr.title << std::endl;
}
Primer plus C++ 第十六章 标准模板库_STL排序函数
于 2012-12-22 15:24:39 首次发布