在使用累加时,C++中的运算符+不匹配

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

本文关键字:运算符 不匹配 C++      更新时间:2023-10-16

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

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;
}
}

错误

问题是您要求编译器添加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被您试图相加的任何内容所取代。

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

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