STL for_each()
http://www.cplusplus.com/reference/algorithm/for_each/
std::move()用于c++11
http://www.cplusplus.com/reference/utility/move/
c++98
// for_each example #include <iostream> // std::cout #include <algorithm> // std::for_each #include <vector> // std::vector void myfunction (int i) { // function: std::cout << ' ' << i; } struct myclass { // function object type: void operator() (int i) {std::cout << ' ' << i;} } myobject; int main () { std::vector<int> myvector; myvector.push_back(10); myvector.push_back(20); myvector.push_back(30); std::cout << "myvector contains:"; for_each (myvector.begin(), myvector.end(), myfunction); std::cout << '\n'; // or: std::cout << "myvector contains:"; for_each (myvector.begin(), myvector.end(), myobject); std::cout << '\n'; return 0; }
c++11 // Returns fn, as if calling std::move(fn)
.
// for_each example #include <iostream> // std::cout #include <algorithm> // std::for_each #include <vector> // std::vector void myfunction (int i) { // function: std::cout << ' ' << i; } struct myclass { // function object type: void operator() (int i) {std::cout << ' ' << i;} } myobject; int main () { std::vector<int> myvector; myvector.push_back(10); myvector.push_back(20); myvector.push_back(30); std::cout << "myvector contains:"; for_each (myvector.begin(), myvector.end(), myfunction); std::cout << '\n'; // or: std::cout << "myvector contains:"; for_each (myvector.begin(), myvector.end(), myobject); std::cout << '\n'; return 0; }
Output:
myvector contains: 10 20 30 myvector contains: 10 20 30STL ==> move()
// move example #include <utility> // std::move #include <iostream> // std::cout #include <vector> // std::vector #include <string> // std::string int main () { std::string foo = "foo-string"; std::string bar = "bar-string"; std::vector<std::string> myvector; myvector.push_back (foo); // copies myvector.push_back (std::move(bar)); // moves std::cout << "myvector contains:"; for (std::string& x:myvector) std::cout << ' ' << x; std::cout << '\n'; return 0; }