STL generate algorithm and functions

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jgoulden
    New Member
    • Nov 2013
    • 1

    STL generate algorithm and functions

    I'm new to the STL and am trying to learn from (dear Lord) the web...at any rate I want to use generate to populate a vector with numbers within a range. Tutorials seem to lead me to code like this, but the compiler always coughs up a "term does not evaluate to a function" error at the function in the generate statement. Can someone point me in the right direction?

    Code:
    #include<vector>
    #include<algorithm>
    #include<iostream>
    #include<cstdlib>
    using namespace std;
    
    class randomInt{
    public:
       randomInt(int i, int j) : min(i), max(j) {}
       int operator()(int min, int max){
         return rand()%(max-min)+min;
       }
    private:
       int min, max;
    };
    
    int main(){
       vector<int> v(50);
       randomInt ri(10,50);
       generate(v.begin(), v.end(), ri);
       for(vector<int>::iterator i = v.begin(); i != v.end(); ++i){
          cout << *i << " ";
       }
    return EXIT_SUCCESS;
    }
    Last edited by Banfa; Nov 20 '13, 10:08 AM.
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    The problem is that you have defined the function call operator has having 2 parameters but generate expects it to have none. Further more because you use a class with instance data those parameters are not required; try:

    Code:
       int operator()(){
         return rand()%(max-min)+min;
       }

    Comment

    • PeterSullivan
      New Member
      • Aug 2013
      • 7

      #3
      Yes I think this could help define call operator perfect class.

      Comment

      Working...