[英]error: no match for ‘operator+’ (operand types are ‘std::vector<int>’ and ‘int’)
I am trying to resolve Fractional Knapsack problem (Maximum Value of the Loot), there is my code:我正在尝试解决分数背包问题(战利品的最大值),有我的代码:
#include <iostream>
#include <vector>
#include <algorithm>
using std::vector;
double get_optimal_value(int capacity, vector<int> weights, vector<int> values) {
double value = 0.0;
vector<int> ratio;
for(int i=0; i<values.size(); i++) {
ratio.push_back(values[i]/weights[i]);
}
int a = 0;
while(capacity>0){
auto it = std::max_element(ratio.begin(), ratio.end());
a = std::max(capacity, *it);
capacity -= *it * a;
values = values + a * *it;
}
return value;
}
And I get the following error:我收到以下错误:
error: no match for 'operator+' (operand types are 'std::vector' and 'int')错误:'operator+' 不匹配(操作数类型为 'std::vector' 和 'int')
For the line:对于线路:
values = values + a * *it;
You probably wanted to do你可能想做
values.push_back(a * *it);
to append the result of a * *it
to the vector
.到 append 的结果a * *it
到vector
。
Shouldn't that line be something like value += a * (*it);
该行不应该类似于value += a * (*it);
? ? That appears to be a typo to me.这对我来说似乎是一个错字。 Probably, you have got confused between value
and values
.可能,您对value
和values
感到困惑。 The latter one is a std::vector<int>
.后一个是std::vector<int>
。 You surely cannot add a number( double
) to a vector
in it that way.您肯定不能以这种方式将数字( double
)添加到vector
中。
If you instead want to add a * (*it)
to every value then probably a simple range-based for loop will work or something like std::transform
.如果您想为每个值添加a * (*it)
,那么可能一个简单的基于范围的 for 循环将起作用,或者类似于std::transform
。 Or if you want to insert that element into the vector, then probably something like push_back()
would do the job for you.或者,如果您想将该元素插入向量中,那么类似push_back()
之类的东西可能会为您完成这项工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.