I am looking at the documentation about std::for_each. (https://cplusplus.com/reference/algorithm/for_each/)
I cannot understand the way they are using the struct myclass
because they are not declaring a variable in main
to pass to for_each
. This is the code:
#include <iostream> // std::cout
#include <algorithm> // std::for_each
#include <vector> // std::vector
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(), myobject);
std::cout << '\n';
return 0;
}
My intuition is that
struct myclass { // function object type:
void operator() (int i) {std::cout << ' ' << i;}
} myobject;
equals to:
struct myclass { // function object type:
void operator() (int i) {std::cout << ' ' << i;}
};
myclass myobject;
So they are declaring the variable (as global) and defining the struct in the same statement. Is it correct?
Aucun commentaire:
Enregistrer un commentaire