1. 程式人生 > 其它 >STL內建演算法代替for迴圈

STL內建演算法代替for迴圈

為什麼要代替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;
}