0
votes

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’)

For the line :

values = values + a * *it;
2
What do you expect that line to do? You are adding a vector (values) to an integer (a * *it). That operation is not defined.Marcel Krüger
Thank you! I just confused value with values.Hitan Elo
Are you confusing your double 'value' var for your vector 'values'?Chris J

2 Answers

1
votes

You probably wanted to do

values.push_back(a * *it);

to append the result of a * *it to the vector.

1
votes

Shouldn't that line be something like value += a * (*it);? That appears to be a typo to me. Probably, you have got confused between value and values. The latter one is a std::vector<int>. You surely cannot add a number(double) to a vector in it that way.

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. Or if you want to insert that element into the vector, then probably something like push_back() would do the job for you.