CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Jul 2005
    Posts
    1,030

    A question regard function object

    Here is the code,
    Code:
    class IntSequence
    {
    public:
    	IntSequence(int initialValue) : value(initialValue) {}
    
    	int operator()()
    	{
    		return value++;
    	}
    
    private:
    	int value;
    };
    
    int main()
    {		
     	list<int> coll;
    
    	generate_n(back_inserter(coll), 9, IntSequence(1));
      	return 0;
    }
    In the call of generate_n, generator function IntSequence(1) with an int argument will call operator() but operator() doesn't have any arguments. I wander why? Also if I define operator() as the follows,
    Code:
    int operator()(int elem)
    {
         return value+elem;
    }
    How can I call generate_n?
    Last edited by LarryChen; July 18th, 2010 at 11:46 PM.

  2. #2
    Join Date
    Jun 2009
    Location
    France
    Posts
    2,513

    Re: A question regard function object

    Gen: Generator function that takes no arguments and returns some value to be stored as element value
    Because the argument is a generator function. That means calling operator()() should generate a new value every time. Like rand(). It doesn't take an argument.

    It could, but that's just not how it's designed.
    Is your question related to IO?
    Read this C++ FAQ article at parashift by Marshall Cline. In particular points 1-6.
    It will explain how to correctly deal with IO, how to validate input, and why you shouldn't count on "while(!in.eof())". And it always makes for excellent reading.

  3. #3
    Join Date
    Aug 2005
    Location
    San Diego, CA
    Posts
    1,054

    Lightbulb Re: A question regard function object

    How can I call generate_n?
    You can't with that second predicate. You can do it with for_each though by designing a predicate that takes a non-const reference to each thing in the container.

    Try something like this.
    Code:
    struct IncrementEach
    {
       IncrementEach(int value) : value(2) {}
       void operator()(int& elem)
       {
          elem += value;
       }
       const int value;
    };
    
    int values[10] = { 0 };
    std::for_each(values, values + 10, IncrementEach(2));
    std::ostream_iterator<int> strmiter(std::cout, "\n");
    std::copy(values, values + 10, strmiter);
    std::cout << std::endl;

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured