容器排序
1 //用于sort中的比较函数,定义为ServiceImpl的静态成员函数,比较Book对象中的m_loan_times成员,
降序排序,同时为了能访问Book类中的私有成员,在Book类中声明为友元函数 2 bool ServiceImpl::big_borrow(Book b1,Book b2) 3 { 4 if(b1.m_loan_times > b2.m_loan_times) 5 { 6 return true; 7 } 8 return false; 9 } 10 11 12 //推荐书籍 13 void ServiceImpl::recommend_book(void) 14 { 15 sort(books.begin(),books.end(),ServiceImpl::big_borrow);//调用系统的快速排序 16 17 //存放已经推荐的书籍 18 map<string,int>m; 19 20 cout << "最受欢迎的前三图书" << endl; 21 unsigned int i = 0; 22 int count = 0; 23 for(i = 0;i < books.size();i++) 24 { 25 if(3 < count) 26 { 27 break; 28 } 29 if(0 != m[books[i].m_name]) //当某本书已经被推荐了,map对应的值大于0,则不打印 30 { 31 continue; 32 } 33 ++m[books[i].m_name]; 34 35 cout << "书名:" << books[i].m_name << " 编号:" << books[i].m_id <<
" 作者:" << books[i].m_author <<" 类型:" << books[i].m_type << endl; 36 37 ++count; 38 } 39 40 }
博客是我在大海中捞到针的神器