cb39a_c++_STL_算法_for_each_transform_比较

cb39a_c++_STL_算法_for_each_transform_比较
for_each() 速度快,不灵活
transform() 速度慢, 非常灵活

STL算法-修改性算法
for_each()
copy()
copy_backward()
transform()
merge()
swap_ranges()
fill()
fill_n()

generate()
generate_n()
replace()
replace_if()
replace_copy()
replace_copy_if()

void square(int &elem)//for_each参数必须是按引用传递,速度快
{
elem = elem*elem;

}
int square2(int elem)//transform不能传引用,传copy,速度慢
{
return elem * elem;
}

int main()
transform(b.begin(), b.end(), b.begin(), square2);

 1 /*cb39a_c++_STL_算法_for_each_transform_比较
 2 for_each() 速度快,不灵活
 3 transform() 速度慢, 非常灵活
 4 
 5 STL算法-修改性算法
 6 for_each()
 7 copy()
 8 copy_backward()
 9 transform()
10 merge()
11 swap_ranges()
12 fill()
13 fill_n()
14 
15 generate()
16 generate_n()
17 replace()
18 replace_if()
19 replace_copy()
20 replace_copy_if()
21 
22 void square(int &elem)//for_each参数必须是按引用传递,速度快
23 {
24     elem = elem*elem;
25 
26 }
27 int square2(int elem)//transform不能传引用,传copy,速度慢
28 {
29     return elem * elem;
30 }
31 
32 int main()
33 transform(b.begin(), b.end(), b.begin(), square2);
34 */
35 
36 #include <iostream>
37 #include <algorithm>
38 #include <vector>
39 
40 using namespace std;
41 void square(int &elem)//for_each参数必须是按引用传递,速度快
42 {
43     elem = elem*elem;
44     
45 }
46 int square2(int elem)//transform不能传引用,传copy,速度慢
47 {
48     return elem * elem;
49 }
50 
51 int main()
52 {
53     vector<int> a;
54     vector<int> b;
55     for (int i = 1; i <= 9; ++i)
56     {
57         a.push_back(i);
58         b.push_back(i);
59     }
60     cout << "向量a:" << endl;
61     for (vector<int>::iterator iter = a.begin(); iter != a.end(); ++iter)
62         cout << *iter << ' ';
63     cout << endl;
64     cout << "使用for_each" << endl;
65     for_each(a.begin(), a.end(), square);//调用square函数
66     for (vector<int>::iterator iter = a.begin(); iter != a.end(); ++iter)
67         cout << *iter << ' ';
68     cout << endl;
69 
70     cout << "向量b:" << endl;
71     for (vector<int>::iterator iter = b.begin(); iter != b.end(); ++iter)
72         cout << *iter << ' ';
73     cout << endl;
74 
75     cout << "使用transform算法,不能传引用" << endl;
76     transform(b.begin(), b.end(), b.begin(), square2);
77 
78     for (vector<int>::iterator iter = b.begin(); iter != b.end(); ++iter)
79         cout << *iter << ' ';
80     cout << endl;
81 
82         
83     return 0;
84 }

 

posted @ 2020-02-23 16:42  txwtech  阅读(194)  评论(0编辑  收藏  举报