According to reliable documentation, std::sort accepts the function object by value. This means the Func being used by std::sort is a copy of FuncObj. This means that when 4 is compared with 4, the copy's flag variable is set to 1, and FuncObj is unchanged. The copy is destroyed when std::sort returns, so this flag is lost.
The simplest solution define int flag as static int flag to that all instances of Func share the same Flag.
If this is not an option, different Funcs must have their own flag, my inclination was to go with a std::shared_ptr. Each default constructed Func would have had it's own flag and shared this flag with any copies made.
However Benjamin Lindley reminds of std::reference_wrapper and this provides a much more convenient solution for the problem. The wrapper is passed by value and copied rather then the Func it references, allowing the source Func to be modified inside std::sort.
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
class Func{
public:
int flag;
Func(): flag(0)
{
}
bool operator()(int &l, int &r)
{
if(l==r)
{
flag = 1;
}
return l > r;
}
};
int main()
{
std::vector<int> a = {11,8,7,6,4,3,4,1};
Func FuncObj = Func();
std::sort(begin(a), end(a), std::reference_wrapper<Func>(FuncObj));
std::cout << FuncObj.flag;
return 0;
}
flagwas not1after sorting, but your code never readsflagat all. Post your actual code that demonstrates the problem.forloop to copy, assign directly to the vector:std::vector<int> a = {11,8,7,6,4,3,4,1};FuncObjis passed by value.std::sortoperates on a copy ofFuncObj,flagis set to ` in the copy ofFuncObjandFuncObjis unchanged.