1

Please have a look at the following code. I've tried using max_element function and find function to complete the task, but shows segmentation error, when compiled. I've checked it is not out of bound. Kindly help me out, Also, if possible kindly suggest me some resource on C++ I know badics, I'm having difficulty in the STL part.

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
double bag( int w, vector<int> values,vector<int> weights){
    int index, ma;
    double W1=0.0;
    double V=0.0;
    while(W1<=w)
    {
ma=*max_element(values.begin(), values.end())   ;
auto it = find(values.begin(), values.end(), ma);
index = distance(values.begin(),it);

if(w-W1>=weights[index])
{
V=V+values[index];
W1=W1+weights[index];
}

else 
{
    V=V+values[index]*(w-W1)/weights[index];
    }
    
    values.erase(it);
    weights.erase(it);
    }
    return V;
}
int main() {
  int n;
  int w;
  double ans;
  std::cin >> n >> w;
  vector<int> values(n);
  vector<int> weights(n);
  for (int i = 0; i < n; i++) {
    std::cin >> values[i] >> weights[i];
  }
    cout<<values[n-1];
    ans = bag(w,values,weights);
    cout<<ans;
} 

1 Answers1

0

You are "dereferencing" what is returning from max_element without checking if it is values.end(), which must not be "dereferenced".

The loop condition while(W1<=w) should be while(!values.empty() && W1<=w).

Also weights.erase(it); is invalid because it is an iterator for values, not weights.

values.erase(it);
weights.erase(it);

should be

weights.erase(std::next(weights.begin(), std::distance(values.begin(), it)));
values.erase(it);
MikeCAT
  • 73,922
  • 11
  • 45
  • 70