同上一篇的例子,在CClass裡加上:
private: class ShowID { public: ShowID() {} ~ShowID() {} void operator() (CStudent student) { std::cout << student.GetID() << std::endl; } };然後把CClass::ShowAll()改寫成以下即可:
std::for_each(this->m_students.begin(), this->m_students.end(), CClass::ShowID());去查一下for_each的寫法就很清楚明瞭了:
// TEMPLATE FUNCTION for_each template<class _InIt, class _Fn1> inline _Fn1 for_each(_InIt _First, _InIt _Last, _Fn1 _Func) { // perform function for each element _DEBUG_RANGE(_First, _Last); _DEBUG_POINTER(_Func); _CHECKED_BASE_TYPE(_InIt) _ChkFirst(_CHECKED_BASE(_First)); _CHECKED_BASE_TYPE(_InIt) _ChkLast(_CHECKED_BASE(_Last)); for (; _ChkFirst != _ChkLast; ++_ChkFirst) _Func(*_ChkFirst); return (_Func); }Effictive C++有說過用泛式演算法會比自己寫個循環還要有效率,而且也比較不容易寫錯,維護也方便許多,嗯!的確如此。
0 意見:
張貼留言