#include <iostream>
using namespace std;
/*
Animal cheapest(string type, Animal a[], int size) that returns the
cheapest animal in a of type type (that is, the cheapest cat or dog).
Note: Assuming you’ve
filled in an array of Animals called shelter, calling cheapest from your
main function would
look like
Animal inexpensive = cheapest(“Dog”, shelter, 20);
*/
struct Animal{
string name = "";
string gender = "";
int age = 0;
int price = 0;
string catOrDog = "";
};
Animal cheapest(string type, Animal a[], int size){
int smallest = a[0].price;
int indexOfSmallest = 0;
for(int i = 0; i<size; i++){
if(a[i].price < smallest && a[i].catOrDog == type){
indexOfSmallest = i;
}
}
return a[indexOfSmallest];
}
void printAnimal(Animal name){
cout<< name.name <<endl;
}
int main(){
Animal arr[1];
Animal one;
one.name = "Chad";
one.gender = "Female";
one.age = 2;
one.price = 1500;
one.catOrDog = "Dog";
Animal two;
two.name = "Brian";
two.gender = "Female";
two.age = 2;
two.price = 1000;
two.catOrDog = "Dog";
arr[0] = one;
arr[1] = two;
Animal inexpensive = cheapest("Dog", arr, 2);
printAnimal(inexpensive);
return 0;
}
运行代码时出现细分错误。根据我搜索过的内容,这通常发生在您从文件读取但我没有从文件读取的情况下。 我的代码有什么问题?这是我第一次遇到这样的问题,所以我完全空白
答案 0 :(得分:1)
您使用 one 元素声明一个数组:
Animal arr[1];
然后通过将两个元素存储到其中来进行访问:
arr[0] = one;
arr[1] = two;
只有第一个索引(0
)有效。
您应该考虑使用std::array
或std::vector
而不是C样式的数组,因此您不必分别传递其大小。