STL for_each()

时间:2021-10-01 17:34:26

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();
myvector.push_back();
myvector.push_back(); 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 ;
}

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();
myvector.push_back();
myvector.push_back(); 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 ;
}

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 ;
}