Question about for_each function

Hello everybody. I am new to the forums, and pretty new to C++ so I have been trying to teach myself (I am fairly familiar with Python and somewhat familiar with Java).

I am trying to write an application to assist me with financial asset trading. I have written two classes called Option and Stock to represent the two financial assets I'll be working with for now. Both Option and Stock have a method called price() which computes the price of the asset.

I have created another class called Position which I am using to store a collection of Options and Stocks. I am doing this by using #include <list> and storing options in an option list, and storing stocks in a stock list.

What I am trying to do is create a method called price() in the Position class that iterates through the two lists and adds up all the prices of the individual assets. I have done this as follows:


void addPriceStock(Stock addStock) {
positionPrice += addStock.price();
}

void addPriceOption(Option addOption) {
positionPrice += addOption.price();
}

void price() {
for_each(stocks.begin(), stocks.end(), addPriceStock);
for_each(options.begin(), options.end(), addPriceOption);
}

positionPrice is a data member of the position class created to store the total.

When I try to compile I get an error stating that the function calls are missing arguments. However, I have tried several things and I have been unable to figure out how to feed the functions addPriceStock and addPriceOption the correct arguments (which should be the Stock or Option that for_each is currently looking at).

I hope I was able to articulate what I am confused about. If anybody could let me know what I am doing wrong I would greatly appreciate it!

Thanks!



Is positionPrice a global variable? If not, how does the function know about it?
You can not use a regular member function in the for_each(), it needs to be a static member function or a non class function. The other possibility is a function object.

http://www.cplusplus.com/reference/algorithm/for_each/
Last edited on
There are other solutions with boost::lambda that make this a one-liner
without requiring additional functions. eg.

1
2
3
4
5
#include <boost/lambda/lambda.hpp>

int positionPrice = 0;  // whatever type
std::for_each( stocks.begin(), stocks.end(),
    boost::lambda::var( positionPrice ) += boost::lambda::bind( &Stock::price, boost::lambda::_1 ) );

Topic archived. No new replies allowed.