lundi 26 octobre 2020

C++ function exits loop with exit code None

This is a problem that's part of a Coursera Algorithms course I am enrolled in. This is not to ask for an answer to the question, but I have been getting nowhere with solving it at all because my code (in the function) runs to the line before the for loop line and then it exits. This is the code:

#include <iostream>
#include <vector>
#include <algorithm>

using std::vector;
using namespace std;

double get_optimal_value(int capacity, vector<int> weights, vector<int> values) {
  double value = 0.0;
  vector<int> rates;
  int len = end(weights) - begin(weights);
  cout << "pre-loop (values loop)" << endl; //the last line the code executes
  for (int i = 0; i < len; i++){
    rates[i] = values[i] / weights[i];
    cout << values[i] / weights[i] << endl; 
  }
  std::sort(begin(rates), end(rates), greater<int>());
  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;
}

The file itself is provided by the instructors, and we only have to work with the function that we're working on, not the main function.

Aucun commentaire:

Enregistrer un commentaire