STL-算法 修改性算法:
for_each() generate()
copy() generate_n()
copy_backwards() replace()
transform() replace_if()
merge() replace_copy()
swap_ranges() replace_copy_if()
fill()
fill_n()
for_each() 速度快 不靈活 只有一個區間的時候用
transform() 速度慢 非常靈活 兩個或者兩個區間只能用transform
#include#include #include using namespace std; // 這個參數必須是引用傳遞,必須要修改 void square(int & elem) { elem = elem * elem; } // transfrom 的要求 參數的傳遞不需要傳引用,傳值就行 ,但是要有返回值 int square2(int elem) { return elem * elem; } int main() { vector a; vector b; for (int i = 1; i <= 9; i++) { a.push_back(i); b.push_back(i); } cout << "向量a:" << endl; for (vector ::iterator iter = a.begin(); iter != a.end(); iter++) cout << *iter << ' '; cout << endl; for_each(a.begin(), a.end(), square);// 速度快,傳引用 for (vector ::iterator iter = a.begin(); iter != a.end(); iter++) cout << *iter << ' '; cout << endl; cout << "向量b:" << endl; for (vector ::iterator iter = b.begin(); iter != b.end(); iter++) cout << *iter << ' '; cout << endl; transform(b.begin(), b.end(), b.begin(), square2);// 速度慢,傳值 for (vector ::iterator iter = b.begin(); iter != b.end(); iter++) cout << *iter << ' '; cout << endl; // system("pause"); return 0; }