在前人的程式碼中挖出一段有趣的find_if應用,我把它改寫成比較好理解的樣式。
例子:一個班級裡有n個學生,現在我們要利用他們的學號來找尋此人。
解析:假設學生是用容器存起來的,我們當然可以直接寫出在容器內收尋id然後再show出來就可以了,不過既然要用find_if,那麼上面的方法自然也就不使用啦。
首先我們先定義學生的資料,這裡我只加個id而已:
04 |
CStudent( int id) : m_id(id) {} |
07 |
int GetID() { return this ->m_id; } |
08 |
void Show() { std::cout << this ->m_id << std::endl; } |
然後再來定義班級的資料,這裡把FindID放進來是因為我不想讓其他人去使用到它,只限用此class可使用:
07 |
void Add(CStudent student) { m_students.push_back(student); } |
11 |
void FindFromID( int id); |
13 |
std::vector<CStudent> m_students; |
20 |
FindID( const int compare_id) : m_compare_id(compare_id) {} |
23 |
bool operator () (CStudent student) { return student.GetID() == this ->m_compare_id; } |
再來定義CClass裡的Function:
01 |
void CClass::ShowAll() |
03 |
for (std::vector<CStudent>::iterator it = this ->m_students.begin(); it != this ->m_students.end(); ++it) |
04 |
std::cout << it->GetID() << std::endl; |
07 |
void CClass::FindFromID( int id) |
10 |
std::vector<CStudent>::iterator it = std::find_if( this ->m_students.begin(), this ->m_students.end(), CClass::FindID(id)); |
11 |
if (it == this ->m_students.end()) |
12 |
std::cout << "Sorry!No find!" << std::endl; |
14 |
std::cout << "Find student ID : " << it->GetID() << std::endl; |
要怎麼使用呢?
2 |
for ( int i = 1; i <= 50; ++i) |
3 |
class01.Add(CStudent(i)); |
6 |
class01.FindFromID(24); |