No match for operator+ in C++ while using accumulate

Viewed 292

I am trying to calculate the average of the entries, but for some reason I am getting an unexpected error:

error: no match for ‘operator+’ (operand types are ‘double’ and ‘const OrderBookEntry’)
  __init = __init + *__first;" 
              ~~~~~~~^~~~~~~~~~

I am new to C++ and tried to solve this for a while, but nothing worked.

int MerkelBot::predictMarketPrice()
{
    int prediction = 0;
    for (std::string const& p : orderBook.getKnownProducts())
    {
        std::cout << "Product: " << p << std::endl;
        std::vector<OrderBookEntry> entries = orderBook.getOrders(OrderBookType::ask, 
                                                                p, currentTime);

    double sum = accumulate(entries.cbegin(), entries.cend(), 0.0);
    prediction =  sum / entries.size();
    std::cout << "Price Prediction is: " << prediction << std::endl;
    }
}

The error

2 Answers

The problem is that you are asking the compiler to add OrderBookEntry objects but the compiler doesn't know how to do that.

You have to tell the compiler what you mean by adding OrderBookEntry objects. One way to do that is to overload operator+

double operator+(double total, const OrderBookEntry& x)
{
    // your code here that adds x to total
}

But probably a better way would be to forget about std::accumulate and just write a for loop to do the addition.

double sum = 0.0;
for (auto const& e : entries)
    sum += e.something(); // your code here

with something replaced by whatever it is that you are trying to add up.

Probably you don't want to add the book entries but the prices of the books. You can pass a function to std::accumulate:

double sum = std::accumulate(entries.cbegin(), entries.cend(), 0.0, [](double sum, const OrderBookEntry &bookEntry) {
    return sum + bookEntry.price;
});
Related