STL內建演算法代替for迴圈
阿新 • • 發佈:2021-10-14
為什麼要代替for迴圈
如果用for,每次的迴圈,都要呼叫函式end ;
for (auto i = tmp.begin(); i != tmp.end(); i++) { i->test(); }
如果改用下面方法則只會呼叫一次end;會大大的提升效率
std::for_each(tmp.begin(), tmp.end(), mem_fun_ref(&A::test));
class A { public: A() { cout << "A"<<endl; } A(const A&) { cout << "A&&&&" << endl; } void test() { cout << 11 << endl; } ~A() { cout << "~A" << endl; } }; int main() { vector<A> tmp; std::cout << " ***************" << endl; A a; std::cout << " ***************" << endl; tmp.push_back(a); std::cout << " ***************" << endl; tmp.push_back(a); std::cout << " ***************" << endl; for (auto i = tmp.begin(); i != tmp.end(); i++) { i->test(); } std::cout << " -----------------" << endl; std::for_each(tmp.begin(), tmp.end(), mem_fun_ref(&A::test)); std::cout << " ++++++++++" << endl; return 0; }