c++ - 结构数组:没有匹配的函数来调用和接受用户输入
问题描述
我已经为背包问题编写了代码。当我对输入进行硬编码时,代码运行良好,但现在我想从结构数组中获取用户的输入,但它显示错误。我该如何实现?原始代码:
#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;
}
解决方案
检查以下代码:
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] 代码中可能存在更多问题,但我查看了您在问题中指出的问题。
推荐阅读
- apache-kafka - Flink 停止静默消费 Kafka 主题
- laravel - Vue SPA 中的角色和权限
- ios - 在 Combine 中将一个发布者转换为另一个发布者
- html - 如何使用 Ruby 在控制台中输出带有 furiga 的汉字?
- apollo-client - 使用订阅时无法在上下文中找到“客户端”或作为选项问题传入
- javascript - 在前端显示 CSS 变量的值
- ios - swift AVAudioEngine 故障
- java - 使用 JavaParser 重构一个 java 文件
- r - R:如果 randomForest() 生成 boostrapped 常量会发生什么?
- ms-access - 如何使用另一列的排序顺序对条形图进行排序?