在使用累加时,C++中的运算符+不匹配
No match for operator+ in C++ while using accumulate
我正在尝试计算条目的平均值,但由于某种原因,我遇到了一个意外错误:
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;
});
相关文章:
- 在使用累加时,C++中的运算符+不匹配
- 我在 .h 中有一个枚举类,并且在.cpp错误中有一个运算符重载:与"运算符<<不匹配
- 为什么我收到错误:"运算符<<不匹配?
- 映射迭代器与运算符不匹配
- 与"运算符>>"不匹配(操作数类型为"QDataStream"和"QJsonObject")
- 与标准中的"运算符<<"不匹配
- 运算符不匹配*=
- 不断收到错误" 与"运算符>>不匹配";
- 编译我的 3 个文件时,我收到错误,说"运算符="不匹配
- C++ 模板与运算符<不匹配
- 与"运算符="不匹配
- 代码块编译错误与运算符<<不匹配
- 错误:运算符 [] 不匹配。在比较列表中的 int 和 int 时<int>,
- 解决错误:运算符 [] 不匹配
- 错误:与"运算符>>"不匹配(操作数类型为"std::istream
- 与"运算符[]"不匹配(操作数类型为"std::unique_ptr<std::vector<int> >"和"int")
- 错误:与“运算符 []”不匹配
- 与"运算符<<不匹配
- 错误:与"运算符[]"不匹配(操作数类型为"QVector<int>"和"QCharRef")
- 错误:"运算符>>"不匹配 重载 istream 运算符