I am trying to write a function object to add the integer values in the map. I have an error in the use of msi as an argument in my function sum. See boldfaced.
Surely using that type of function object is pointless now that we have std::function?
std::function does not define function objects. It just provides us with a generic way to handle things that can behave like functions, such as the function object defined above.
If you were speaking of lambdas that would make more sense, but lambdas are not the panacea of function objects.
I did as you said, and the program worked beautifully.
andywestkin,
You're right. I did not write a function object but wrote a function instead. I honestly did not know until I re-read the section on function objects. I am glad, however, I wrote the function first because as you can see I did not know how to write the function. The mistakes I made were worth the learning experience. Thank you, MiiNiPaa.
I used your function object in my program but it did not work. I get too many parameters for this operator function for lines 14 and 21 in my code above.
shadowmouse,
A function object is an object that can behave like a function. You use an object because it can store data. The function call operator()implements the "function call".
Leading up from the function and the function object is the lambda expression. From the function, I was able to see the lambda expression, [](int v, std::pair<const std::string, int>& e) { return v + e.second; } . I used it as the last argument in the accumulate algorithm.
A lambda expression is a short hand notation for defining a function object. It can be found in one place as opposed to a function or function object.
I used your function object in my program but it did not work. I get too many parameters for this operator function for lines 14 and 21 in my code above.
The code fragment I posted runs using C+ Shell so you can see how it's supposed to be used.
But I don't get why you should get an error on lines 14 and 21 -- these lines have absolutely nothing to do with the function object (they're the insertion and extraction operators for your map, yes?)
Your function object works. I deleted out all my comments to start anew and the red squiggly lines disappeared. Essentially, I had commented out the function and lambda expression and inserted your function object. So, the error must have been that I did not comment out a code fragment.