1 / transform algorithm example 2 #include <iostream> // std::cout 3 #include <algorithm> // std::transform 4 #include <vector> // std::vector 5 #include <functional> // std::plus 6 7 int op_increase (int i) { return ++i; } 8 9 int main () { 10 std::vector<int> foo; 11 std::vector<int> bar; 12 13 // set some values: 14 for (int i=1; i<6; i++) 15 foo.push_back (i*10); // foo: 10 20 30 40 50 16 17 bar.resize(foo.size()); // allocate space 18
//將foo中的每個元素執行op_increase操作,然後將值寫入bar 19 std::transform (foo.begin(), foo.end(), bar.begin(), op_increase); 20 // bar: 11 21 31 41 51 21
//將foo和bar中的每個元素執行plus操作,然後寫入第一個元素 22 // std::plus adds together its two arguments: 23 std::transform (foo.begin(), foo.end(), bar.begin(), foo.begin(), std::plus<int>()); 24 // foo: 21 41 61 81 101 25 26 std::cout << "foo contains:"; 27 for (std::vector<int>::iterator it=foo.begin(); it!=foo.end(); ++it) 28 std::cout << ' ' << *it; 29 std::cout << '\n'; 30 31 return 0; 32 }