【问题标题】:No match for operator+ in C++ while using accumulate使用累积时 C++ 中的 operator+ 不匹配
【发布时间】:2020-07-06 07:31:02
【问题描述】:

我正在尝试计算条目的平均值,但由于某种原因,我遇到了意外错误:

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

我是 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

【问题讨论】:

  • 如何“添加”两个OrderBookEntry 对象?也许您应该使用std::accumulate 的重载,在其中提供执行“添加”的谓词?

标签: c++ operator-overloading accumulate


【解决方案1】:

问题是您要求编译器添加 OrderBookEntry 对象,但编译器不知道该怎么做。

您必须通过添加OrderBookEntry 对象来告诉编译器您的意思。一种方法是重载operator+

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

但可能更好的方法是忘记std::accumulate,只写一个for循环来做加法。

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

something 替换为您尝试添加的任何内容。

【讨论】:

    【解决方案2】:

    您可能不想添加图书条目,而是添加图书的价格。您可以将函数传递给std::accumulate

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

    【讨论】:

      猜你喜欢
      • 2011-02-21
      • 2019-04-09
      • 2021-05-21
      • 2015-09-09
      • 1970-01-01
      • 2011-12-10
      • 2013-07-31
      • 2018-12-05
      • 1970-01-01
      相关资源
      最近更新 更多