首页 > 解决方案 > 结构数组:没有匹配的函数来调用和接受用户输入

问题描述

我已经为背包问题编写了代码。当我对输入进行硬编码时,代码运行良好,但现在我想从结构数组中获取用户的输入,但它显示错误。我该如何实现?原始代码:

#include<iostream>
#include<algorithm>
using namespace std;
struct Item{
    int value;
    int weight;
    Item(int value,int weight):value(value),weight(weight){

    }
};

bool cmp(struct Item a,struct Item b){
    float r1=(float)a.value/a.weight;
    float r2=(float)b.value/b.weight;
    //cout<<r1<<" "<<r2<<endl;
    return r1>r2;
}

void knapsack(int m,int n,struct Item arr[]){
    sort(arr,arr+n,cmp);
   /* for(int i=0;i<n;i++){ //new sorted array
        cout<<arr[i].value<<" "<<arr[i].weight<<" ";
    }*/
    cout<<endl;
    float result[n];
    for(int i=0;i<n;i++){
        result[i]=0.0;
    }
    int rem=m;
    int j=0;
    for(j=0;j<n;j++){
        if(arr[j].weight>rem){
            break;
        }
        else{
            result[j]=1;
            rem=rem-arr[j].weight;
        }
    }
    if(j<n){
        result[j]=(float)rem/arr[j].weight;
    }
    for(int k=0;k<n;k++){
        cout<<result[k]<<" ";
    }
}

int main(){
    struct Item arr[]={{25,18},{24,15},{15,10}};
    knapsack(20,3,arr);
    return 0;
}

现在我想在结构数组中获取用户输入,但它显示错误“没有要调用的匹配函数”

#include<iostream>
#include<algorithm>
using namespace std;
struct Item{
    int value;
    int weight;
    Item(int value,int weight):value(value),weight(weight){

    }
};

bool cmp(struct Item a,struct Item b){
    float r1=(float)a.value/a.weight;
    float r2=(float)b.value/b.weight;
    //cout<<r1<<" "<<r2<<endl;
    return r1>r2;
}

void knapsack(int m,int n,struct Item arr[]){
    sort(arr,arr+n,cmp);
   /* for(int i=0;i<n;i++){ //new sorted array
        cout<<arr[i].value<<" "<<arr[i].weight<<" ";
    }*/
    cout<<endl;
    float result[n];
    for(int i=0;i<n;i++){
        result[i]=0.0;
    }
    int rem=m;
    int j=0;
    for(j=0;j<n;j++){
        if(arr[j].weight>rem){
            break;
        }
        else{
            result[j]=1;
            rem=rem-arr[j].weight;
        }
    }
    if(j<n){
        result[j]=(float)rem/arr[j].weight;
    }
    for(int k=0;k<n;k++){
        cout<<result[k]<<" ";
    }
}

int main(){
    struct Item arr[10];
    int n,m;
    cin>>m>>n;
    for(int i=0;i<n;i++){
        cin>>arr[i].value>>arr[i].weight;
    }
    knapsack(m,n,arr);
    return 0;
}

标签: c++

解决方案


检查以下代码:

struct Item{
    int value;
    int weight;
    Item(int value,int weight):value(value),weight(weight){

    }
};

没有默认构造函数。所以下面的行失败了:

struct Item arr[10];

但以下行有效:

struct Item arr[]={{25,18},{24,15},{15,10}};

解决方案[1]:提供默认构造函数或移除显式构造函数。


[1] 代码中可能存在更多问题,但我查看了您在问题中指出的问题。


推荐阅读