分数背包算法分割错误

Fractional Knapsack Algorithm segmentation fault

我正在尝试通过编写一个函数 get_optimal_value 来解决分数背包问题,该函数 returns 给定背包容量以及物品的重量和价值的总最优值。在函数 get_optimal_value 中,我 运行 遇到了 v_per_w[i] = values[i]/weights[i]; 上的分段错误问题,我不确定发生了什么,因为我看不到我在哪里访问了外部内存. 这是我的程序。帮助将不胜感激谢谢 :D

#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<double> v_per_w = {};
  for (int i =0; i<weights.size(); ++i){
    v_per_w[i] = values[i]/weights[i]; //calculate v/w for the vector
  }

  //as long as capacity is not full
  while (capacity !=0){
    auto it = std::max_element(v_per_w.begin(), v_per_w.end()); //find max element in v/w
    auto it2 = find(v_per_w.begin(), v_per_w.end(), *it); // find the index of that max element in v/w
    int largest_index = it2 - v_per_w.begin(); 
    if (capacity>=weights[largest_index]){ 
      value+= values[largest_index]; //if capacity is more than the weight of that max v/w, add it all in
    }
    else{
      value += v_per_w[largest_index] * capacity; //else add whatever weight you can of that max v/w
    }
    values.erase(values.begin(), values.begin()+largest_index-1); //remove that item from all the vectors
    weights.erase(weights.begin(), weights.begin()+largest_index-1);
    v_per_w.erase(v_per_w.begin(), v_per_w.begin()+largest_index-1);
  }

  return value;
}

int main() {
  int n;
  int capacity;
  std::cin >> n >> capacity;
  vector<int> values(n);
  vector<int> weights(n);
  for (int i = 0; i < n; i++) {
    std::cin >> values[i] >> weights[i];
  }

  double optimal_value = get_optimal_value(capacity, weights, values);

  std::cout.precision(10);
  std::cout << optimal_value << std::endl;
  return 0;
}
vector<double> v_per_w = {};

这将创建一个新的 vector,它完全是空的。它没有任何价值。紧接着:

v_per_w[i] = values[i]/weights[i]; //calculate v/w for the vector

这会尝试更改 v_per_w 的现有值。但是,由于 v_per_w 完全是空的,所以它没有任何值;这几乎可以肯定会产生您所观察到的崩溃类型。 v_per_w[something] 不向向量添加新值。它 modifies/accesses 向量中的现有值,必须已经存在。