简体   繁体   English

使用累积时 C++ 中的 operator+ 不匹配

[英]No match for operator+ in C++ while using accumulate

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.我是 C++ 的新手,并试图解决这个问题一段时间,但没有任何效果。

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错误

The problem is that you are asking the compiler to add OrderBookEntry objects but the compiler doesn't know how to do that.问题是您要求编译器添加OrderBookEntry对象,但编译器不知道如何执行此操作。

You have to tell the compiler what you mean by adding OrderBookEntry objects.您必须通过添加OrderBookEntry对象来告诉编译器您的意思。 One way to do that is to overload operator+一种方法是重载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.但可能更好的方法是忘记std::accumulate并只编写一个 for 循环来进行加法。

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.用你想要加起来的something代替。

Probably you don't want to add the book entries but the prices of the books.可能您不想添加书籍条目,而是添加书籍的价格。 You can pass a function to std::accumulate :您可以将 function 传递给std::accumulate

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM