I want just to print a vector with for_each.
using namespace std;
struct Print {
int z = 0;
void operator()(int i) {
if (z) cout << ' ';
cout << i;
z = 1;
}
~Print() {
if (z) cout << endl;
}
};
main() {
vector<int> v = {1, 2, 3, 4, 5};
for_each(begin(v), end(v), Print());
}
It works wrong, it calls destructor two times and prints two newlines instead of one. Why? Can anybody explain the logic of this odd behavior? BTW it works fine with the ugly global variable.
int z;
struct Print {
void operator()(int i) {
. . .
};
I am using GCC.