问题
In this code below I can´t understand really well how can std::generate(v2.begin(), v2.end(), r)
call the rand() if there isn´t the operator () in r or even any parameters on it.
class RandomInt
{
public:
RandomInt(int a, int b);
int operator()();
private:
int limInf, limSup; // interval limits: [limInf..limSup]
};
//----------------------------------------------------------------------
RandomInt::RandomInt(int a, int b)
{
limInf = a; limSup = b;
}
//----------------------------------------------------------------------
int RandomInt::operator()()
{
return limInf + rand() % (limSup - limInf + 1);
}
//----------------------------------------------------------------------
//----------------------------------------------------------------------
int main() {
srand((unsigned)time(NULL));
std::vector<int> v2(10);
int limInf, limSup;
std::cout << "limInf ? "; std::cin >> limInf;
std::cout << "limSup ? "; std::cin >> limSup;
RandomInt r(limInf, limSup); //instantiates object and sets limits
std::generate(v2.begin(), v2.end(), r);
// ALTERNATIVE:
// using an unnamed temporary that will be destroyed at the end of the call
//generate(v2.begin(),v2.end(),RandomInt(limInf,limSup));
displayVec("random numbers", v2);
return 0;
}
来源:https://stackoverflow.com/questions/62116060/understanding-the-use-of-operator-function-object