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 }