In trying to answer this question I came up with the following code:
#include <string>
#include <iostream>
#include <algorithm>
#include <vector>
class Sizes
{
public:
void operator() ( std::vector<int> v ) {
sizeVec.push_back( v.size() );
}
std::vector<int> sizeVec;
};
void outFunc (int i) {
std::cout << " " << i;
}
int _tmain(int argc, _TCHAR* argv[])
{
std::vector<std::vector<int>> twodVec;
std::vector<int> vec;
vec.push_back( 6 );
twodVec.push_back( vec );
vec.push_back( 3 );
twodVec.push_back( vec );
vec.push_back( 8 );
twodVec.push_back( vec );
vec.push_back( 3 );
twodVec.push_back( vec );
Sizes sizes;
std::for_each( twodVec.begin(), twodVec.end(), sizes );
std::for_each( sizes.sizeVec.begin(), sizes.sizeVec.end(), outFunc );
return 0;
}
Debugging this shows Sizes::operator() being called and the size of sizeVec increasing with each call as expected. However when the second std::foreach is called the sizeVec is empty… I’ve created a work around involving passing a vector into Sizes but does anyone know what’s going on
std::for_eachtakes a functor by value, not by reference, so the original object is unaffected. You need to do: